import Link from 'next/link'
import { redirect } from 'next/navigation'

import { ConsoleShell } from '@/components/console/shell'
import { getCurrentUser } from '@/lib/auth/current-user'
import { getI18n } from '@/lib/i18n/server'
import { visibleGroups, visibleSpecials } from '@/lib/navigation'
import { buildLiveSnapshot } from '@/lib/services/live-snapshot'
import { prisma } from '@/lib/db'

export const dynamic = 'force-dynamic'

export default async function ConsoleLayout({ children }: { children: React.ReactNode }) {
  const user = await getCurrentUser()
  if (!user) redirect('/login')

  const { t } = await getI18n()

  // The first snapshot is rendered on the server so every tile has real values before
  // the live stream connects — no empty dashboard, even for a second.
  const initialSnapshot = user.permissions.has('grid.read')
    ? await buildLiveSnapshot().catch(() => null)
    : null

  // Data health for the command bar: the mean confidence across everything the platform
  // has scored, rather than an assertion that the feed is fine (§32).
  const dataHealth = await prisma.dataQualityScore
    .aggregate({ _avg: { score: true } })
    .then((result) => (result._avg.score === null ? null : Math.round(result._avg.score * 10) / 10))
    .catch(() => null)

  return (
    <ConsoleShell
      user={{
        name: user.name,
        nameAr: user.nameAr,
        email: user.email,
        role: user.roles[0] ?? 'viewer',
      }}
      groups={visibleGroups(user.permissions)}
      specials={visibleSpecials(user.permissions)}
      initialSnapshot={initialSnapshot}
      permissions={[...user.permissions]}
      dataHealth={dataHealth}
      footer={
        <Link
          href="/why-nabdh"
          className="block rounded-lg border border-border bg-surface-2/60 px-3 py-2.5 transition-colors hover:border-brand/40"
        >
          <p className="text-xs font-medium text-brand">{t('why.title')}</p>
          <p className="mt-0.5 text-[10px] leading-tight text-text-faint">{t('common.tagline')}</p>
        </Link>
      }
    >
      {children}
    </ConsoleShell>
  )
}
