import 'server-only'

import { cache } from 'react'
import { getSessionUser, type SessionUser } from '@/lib/auth'
import {
  ADMIN_WORKSPACES, adminWorkspace, adminWorkspaceForContext, contextDashboard, findContext, resolveLanding,
  switchableContexts, type AdminWorkspace, type Landing, type UserContext,
} from '@/lib/domain/modes'
import { loadModePreferences, loadUserContexts, modesAvailable } from '@/lib/data/modes'
import type { PageContext } from '@/lib/page-context'

/**
 * The mode the request is being served in (Nash, 2026-09-24).
 *
 * The session names a context; the server re-reads what the person actually
 * holds and decides. A cookie never grants a role (§25).
 *
 * `cache` keeps it to one lookup per request even though several components
 * ask for it.
 */
export interface ActiveMode {
  user: SessionUser
  /** Everything the person holds: active, pending and past. */
  contexts: UserContext[]
  /** The mode being used now, or null when nothing is active or an admin is in admin tools. */
  active: UserContext | null
  defaultKey: string | null
  landing: Landing
  /** True when migration 0034 is applied; false means single-role behaviour. */
  available: boolean
  /* Admin */
  isAdmin: boolean
  adminWorkspaces: AdminWorkspace[]
  /** The product view an admin is previewing, if any. */
  preview: AdminWorkspace | null
  adminDefault: string | null
}

export const loadActiveMode = cache(async (): Promise<ActiveMode | null> => {
  const user = await getSessionUser()
  if (!user) return null
  const isAdmin = user.role === 'admin'
  const available = await modesAvailable()
  const [contexts, prefs] = await Promise.all([loadUserContexts(user), loadModePreferences(user.id)])
  const requested = findContext(switchableContexts(contexts), user.contextKey)
  const landing = resolveLanding(contexts, prefs.defaultKey)
  const active = requested ?? (landing.kind === 'open' ? landing.context : null)
  return {
    user,
    contexts,
    active,
    defaultKey: prefs.defaultKey,
    landing,
    available,
    isAdmin,
    adminWorkspaces: isAdmin ? ADMIN_WORKSPACES : [],
    preview: isAdmin ? adminWorkspace(user.previewWorkspace) : null,
    adminDefault: prefs.adminWorkspace,
  }
})

/** Which page group the request should be served in right now. */
export function activePageContext(mode: ActiveMode | null): PageContext | null {
  if (!mode) return null
  if (mode.isAdmin && mode.preview?.pageContext) return mode.preview.pageContext
  return mode.active?.pageContext ?? null
}

/**
 * May this person open a route of that page group, and where do they go if
 * not? An admin may open anything (§14); everyone else only page groups they
 * hold an active role for (§12).
 */
export function routeDecision(mode: ActiveMode | null, routeCtx: PageContext): { allow: true } | { allow: false; redirect: string } {
  if (!mode) return { allow: false, redirect: '/login' }
  if (mode.isAdmin) return { allow: true }
  const holds = switchableContexts(mode.contexts).filter((c) => c.pageContext === routeCtx)
  if (holds.length === 0) {
    const home = mode.active ? contextDashboard(mode.active) : mode.landing.kind === 'choose' ? '/modes' : '/profile'
    return { allow: false, redirect: home }
  }
  return { allow: true }
}

/** The admin preview that matches a page group, for the preview bar. */
export function previewForRoute(routeCtx: PageContext): AdminWorkspace | null {
  return adminWorkspaceForContext(routeCtx)
}
