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 { loadActiveMode, routeDecision } from '@/lib/data/active-mode'
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')
  // Multi-role accounts (2026-09-24): the decision comes from the roles the
  // person actually holds, not from one account role. Falls back to the old
  // single-role rule while migration 0034 is not applied.
  const mode = await loadActiveMode()
  if (mode?.available) {
    const decision = routeDecision(mode, routeCtx)
    if (!decision.allow) redirect(decision.redirect)
  } else {
    const accountCtx = contextForAccount(user.role)
    if (!mayOpenContext(routeCtx, accountCtx, user.internal)) redirect(dashboardPath(accountCtx))
  }
  const profile = (await getProfile())!
  return { user, profile }
}
