/**
 * T8 · Step-up auth before OPENING a session (not just at login). A fresh login is NOT sufficient:
 * before dropping into a live root-capable shell, presence must be re-asserted. Enforced in T12's
 * `onUpgrade`/`onReattach` (v0.10 augmentation), not merely asserted in prose (Finding-3).
 *
 * `hostContentSecret` browser-delivery gate (§4.5 / FIX 3): a fresh step-up here is ALSO the gate
 * for releasing the host-scoped content secret to an authorized browser device (unwrapped only when
 * `needsStepUp` is false). P5 does not mint/wrap it (P3 mints+wraps at BIND, P2 unwraps for the
 * agent) — P5 only performs the step-up-gated release; a revoked host/device (T10) can no longer
 * obtain it (INV12). See PLAN §T8.
 */
import type { HostRecord } from 'relay-contracts'
import type { AuthMethod, AuthenticatedPrincipal, StepUpPolicy } from '../../types.js'

export const DEFAULT_STEPUP_MAX_AGE_SECONDS = 300 as const

/** Per-host step-up freshness requirement (default: recent passkey step-up REQUIRED). */
export function policyForHost(_host: HostRecord): StepUpPolicy {
  return { required: true, maxAgeSeconds: DEFAULT_STEPUP_MAX_AGE_SECONDS, requiredMethod: 'passkey' }
}

/** v0.9 "never required" default: step-up gate is off (used until per-host tiers exist). */
export const NO_STEPUP_POLICY: StepUpPolicy = {
  required: false,
  maxAgeSeconds: DEFAULT_STEPUP_MAX_AGE_SECONDS,
  requiredMethod: 'passkey',
}

/**
 * true when step-up is required: never stepped up, OR the last step-up is stale, OR the LAST step-up
 * was not performed with the required method (method-binding, F1) — i.e. neither a fresh login nor a
 * weaker (e.g. TOTP) step-up satisfies a passkey requirement.
 */
export function needsStepUp(
  principal: AuthenticatedPrincipal,
  policy: StepUpPolicy,
  now: number,
): boolean {
  if (principal.stepUpAt === null) return true
  if (now - principal.stepUpAt > policy.maxAgeSeconds) return true
  if ((principal.stepUpMethod ?? null) !== policy.requiredMethod) return true
  return false
}

/**
 * Returns a NEW principal recording a fresh step-up: `stepUpAt = now`, `stepUpMethod = method`, and
 * `method` appended to `amr` (audit trail). Immutable — the original is untouched.
 */
export function recordStepUp(
  principal: AuthenticatedPrincipal,
  method: AuthMethod,
  now: number,
): AuthenticatedPrincipal {
  const amr = principal.amr.includes(method) ? principal.amr : [...principal.amr, method]
  return { ...principal, amr, stepUpAt: now, stepUpMethod: method }
}
