import { redirect } from 'next/navigation'
import type { Route } from 'next'
import { auth } from '@/lib/auth'
import type { UserRole } from '@prisma/client'

const ROLE_DASHBOARDS: Record<string, string> = {
  SUPER_ADMIN: '/admin',
  PROGRAM_ADMIN: '/admin',
  JURY_MEMBER: '/jury',
  MENTOR: '/mentor',
  OBSERVER: '/observer',
  APPLICANT: '/applicant',
}

export async function requireRole(...allowedRoles: UserRole[]) {
  const session = await auth()

  if (!session?.user) {
    redirect('/login')
  }

  // Use roles array, fallback to [role] for stale JWT tokens
  const userRoles = session.user.roles?.length ? session.user.roles : [session.user.role]

  if (!allowedRoles.some(r => userRoles.includes(r))) {
    const dashboard = ROLE_DASHBOARDS[session.user.role]
    redirect((dashboard || '/login') as Route)
  }

  return session
}
