import type { Metadata } from 'next'
import { cookies } from 'next/headers'
import { AdminDashboard, type DashboardData } from '@/components/admin-dashboard'
import { djangoUrl } from '@/lib/site-content'

export const metadata: Metadata = {
  title: 'RG Admin Panel | Dashboard',
  description: 'RG Fish Farming operations dashboard.',
}

export default async function DashboardPage() {
  const cookieHeader = (await cookies()).toString()
  let initialData: DashboardData | null = null
  let initialError = ''

  try {
    const response = await fetch(djangoUrl('/api/dashboard/?range=7'), {
      headers: cookieHeader ? { cookie: cookieHeader } : undefined,
      cache: 'no-store',
      signal: AbortSignal.timeout(8000),
    })
    if (response.ok) {
      initialData = await response.json() as DashboardData
    } else if (response.status === 401) {
      // The Django session cookie belongs to the API origin, so the client
      // fetch must perform the authenticated check after hydration.
      initialError = ''
    } else if (response.status === 403) {
      initialError = 'You do not have permission to open this dashboard.'
    } else {
      initialError = 'The Django dashboard API returned an error.'
    }
  } catch {
    initialError = 'The Django dashboard API is unavailable.'
  }

  return <AdminDashboard initialData={initialData} initialError={initialError} />
}
