import { redirect } from 'next/navigation'
import { prisma } from '@/lib/prisma'
import { requireRole } from '@/lib/auth-redirect'
import { ObserverNav } from '@/components/layouts/observer-nav'
import { EditionProvider } from '@/components/observer/observer-edition-context'

export const dynamic = 'force-dynamic'

export default async function ObserverLayout({
  children,
}: {
  children: React.ReactNode
}) {
  const session = await requireRole('OBSERVER')
  const isImpersonating = !!session.user.impersonating

  // Check if user has completed onboarding (skip during impersonation)
  if (!isImpersonating) {
    const user = await prisma.user.findUnique({
      where: { id: session.user.id },
      select: { onboardingCompletedAt: true },
    })

    if (!user) {
      redirect('/login')
    }

    if (!user.onboardingCompletedAt) {
      redirect('/onboarding')
    }
  }

  return (
    <div className="min-h-screen bg-background">
      <EditionProvider>
        <ObserverNav
          user={{
            name: session.user.name,
            email: session.user.email,
          }}
        />
        <main className="container-app py-6">{children}</main>
      </EditionProvider>
    </div>
  )
}
