import { redirect } from 'next/navigation'
import { prisma } from '@/lib/prisma'
import { requireRole } from '@/lib/auth-redirect'
import { MentorNav } from '@/components/layouts/mentor-nav'

export const dynamic = 'force-dynamic'

export default async function MentorLayout({
  children,
}: {
  children: React.ReactNode
}) {
  const session = await requireRole('MENTOR', 'PROGRAM_ADMIN', 'SUPER_ADMIN')

  // Check if user has completed onboarding (for mentors)
  const userRoles = session.user.roles?.length ? session.user.roles : [session.user.role]
  if (userRoles.includes('MENTOR') && !userRoles.some(r => r === 'SUPER_ADMIN' || r === 'PROGRAM_ADMIN')) {
    const user = await prisma.user.findUnique({
      where: { id: session.user.id },
      select: { onboardingCompletedAt: true },
    })

    if (!user) {
      // User was deleted — session is stale, send to login
      redirect('/login')
    }

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

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