import { redirect } from 'next/navigation'
import Link from 'next/link'
import { getCurrentUser } from '@/lib/session'
import { execAgent } from '@/lib/agent-client'
import CaddyEditor from '../_components/caddy-editor'

export const dynamic = 'force-dynamic'

export default async function CaddyEditPage() {
  const user = await getCurrentUser()
  if (!user) redirect('/login')

  let initialContent = ''
  let initialError: string | null = null
  try {
    initialContent = await execAgent('caddy_show_config')
  } catch (err) {
    initialError = err instanceof Error ? err.message : 'failed to load config'
  }

  return (
    <div className="min-h-screen bg-background p-6">
      <div className="mx-auto max-w-4xl space-y-6">
        <div className="flex items-center gap-4">
          <Link
            href="/caddy"
            className="text-sm text-muted-foreground hover:text-foreground transition-colors"
          >
            ← Caddy
          </Link>
          <div>
            <h1 className="text-2xl font-semibold tracking-tight">Edit Caddyfile</h1>
            <p className="text-sm text-muted-foreground">
              Edit, validate, then save and reload Caddy
            </p>
          </div>
        </div>

        <CaddyEditor initialContent={initialContent} initialError={initialError} />
      </div>
    </div>
  )
}
