import Link from 'next/link'
import { redirect } from 'next/navigation'
import { getCurrentUser } from '@/lib/session'
import { execAgent } from '@/lib/agent-client'
import UnitDetail from './_components/unit-detail'

export const dynamic = 'force-dynamic'

type Props = {
  params: Promise<{ unit: string }>
}

function getAllowedUnits(): string[] {
  return (process.env.SYSTEMD_UNITS ?? '')
    .split(',')
    .map((u) => u.trim())
    .filter(Boolean)
}

export default async function SystemdUnitPage({ params }: Props) {
  const user = await getCurrentUser()
  if (!user) redirect('/login')

  const { unit } = await params
  const unitName = decodeURIComponent(unit)

  if (!getAllowedUnits().includes(unitName)) {
    return (
      <div className="min-h-screen bg-background p-6">
        <div className="mx-auto max-w-6xl space-y-6">
          <div className="flex items-center gap-3">
            <Link href="/systemd" className="text-sm text-muted-foreground hover:text-foreground">
              ← systemd Units
            </Link>
          </div>
          <div className="rounded-lg border border-destructive/30 bg-destructive/10 px-4 py-3 text-sm text-destructive">
            Unit &quot;{unitName}&quot; not found in SYSTEMD_UNITS.
          </div>
        </div>
      </div>
    )
  }

  let initialStatusOutput = ''
  let initialJournalOutput = ''
  let initialError: string | null = null

  try {
    const [statusOut, journalOut] = await Promise.all([
      execAgent('systemctl_status', [unitName]),
      execAgent('journalctl_recent', [unitName]),
    ])
    initialStatusOutput = statusOut
    initialJournalOutput = journalOut
  } catch (err) {
    initialError = err instanceof Error ? err.message : 'Failed to fetch unit data'
  }

  return (
    <div className="min-h-screen bg-background p-6">
      <div className="mx-auto max-w-6xl space-y-6">
        <div className="flex items-center gap-3">
          <Link href="/systemd" className="text-sm text-muted-foreground hover:text-foreground">
            ← systemd Units
          </Link>
          <span className="text-muted-foreground">/</span>
          <h1 className="text-2xl font-semibold tracking-tight font-mono">{unitName}</h1>
        </div>
        <UnitDetail
          unitName={unitName}
          initialStatusOutput={initialStatusOutput}
          initialJournalOutput={initialJournalOutput}
          initialError={initialError}
        />
      </div>
    </div>
  )
}
