import { redirect } from 'next/navigation'
import { getCurrentUser } from '@/lib/session'
import { execAgent } from '@/lib/agent-client'
import { parseDockerPs, type Container } from '@/lib/parse-docker'
import DockerTable from './_components/docker-table'

export const dynamic = 'force-dynamic'

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

  let initialContainers: Container[] = []
  let initialError: string | null = null

  try {
    const output = await execAgent('docker_ps')
    initialContainers = parseDockerPs(output)
  } catch (err) {
    initialError = err instanceof Error ? err.message : 'Failed to fetch containers'
  }

  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">Docker Containers</h1>
          <p className="text-sm text-muted-foreground">Auto-refreshes every 5 seconds</p>
        </div>
        <DockerTable initialContainers={initialContainers} initialError={initialError} />
      </div>
    </div>
  )
}
