import { redirect } from 'next/navigation'
import { getCurrentUser } from '@/lib/session'
import { execAgent } from '@/lib/agent-client'
import { parseSystemctlStatus, type UnitStatus } from '@/lib/parse-systemd'
import SystemdUnitsList from './_components/systemd-units-list'

export const dynamic = 'force-dynamic'

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

  const units = (process.env.SYSTEMD_UNITS ?? '')
    .split(',')
    .map((u) => u.trim())
    .filter(Boolean)

  const initialUnits = await Promise.all(
    units.map(async (unit) => {
      let status: UnitStatus | null = null
      let error: string | null = null
      try {
        const output = await execAgent('systemctl_status', [unit])
        status = parseSystemctlStatus(output, unit)
      } catch (err) {
        error = err instanceof Error ? err.message : 'failed'
      }
      return { unit, status, error }
    }),
  )

  return (
    <div className="min-h-screen bg-background p-6">
      <div className="mx-auto max-w-6xl space-y-6">
        <div>
          <h1 className="text-2xl font-semibold tracking-tight">systemd Units</h1>
          <p className="text-sm text-muted-foreground">Auto-refreshes every 10 seconds</p>
        </div>
        {units.length === 0 ? (
          <div className="rounded-lg border border-border p-6 text-sm text-muted-foreground">
            No units configured. Set <code className="font-mono">SYSTEMD_UNITS</code> in your
            environment (comma-separated unit names).
          </div>
        ) : (
          <SystemdUnitsList initialUnits={initialUnits} />
        )}
      </div>
    </div>
  )
}
