import 'server-only'
import { redirect } from 'next/navigation'
import { getProfile, getSessionUser, type SessionUser } from '@/lib/auth'
import { contextForAccount, dashboardPath, mayOpenContext, type PageContext } from '@/lib/page-context'
import type { Profile } from '@/types/db'

/**
 * Entry guard for every role route (article §5–§6, 2026-09-13): sign-in
 * required; a customer may open only their own role's pages — anything else
 * sends them to their own dashboard. Internal admins may open any role's
 * pages (testing). Returns the session and profile the page renders with.
 */
export async function requireRoleRoute(routeCtx: PageContext): Promise<{ user: SessionUser; profile: Profile }> {
  const user = await getSessionUser()
  if (!user) redirect('/login')
  const accountCtx = contextForAccount(user.role)
  if (!mayOpenContext(routeCtx, accountCtx, user.internal)) redirect(dashboardPath(accountCtx))
  const profile = (await getProfile())!
  return { user, profile }
}
