/**
 * T12 · Enforcement entry point `onReattach` — deny-by-default on REATTACH too (INV6). Same pipeline
 * as `onUpgrade` but the authz step additionally re-validates that the session exists AND belongs to
 * the same account (INV6 re-validate). P3 calls this on every reattach; a stale-step-up principal
 * never regains a live stream.
 */
import { authorizeReattach, type AuthzOutcome } from '../authz/decide.js'
import { runEnforcement, type EnforceDeps, type UpgradeContext } from './onUpgrade.js'

export type ReattachContext = UpgradeContext & { readonly sessionId: string }

export function onReattach(
  ctx: ReattachContext,
  deps: EnforceDeps,
  allowedOrigins: readonly string[],
  now: number,
): Promise<AuthzOutcome> {
  return runEnforcement(
    ctx,
    deps,
    allowedOrigins,
    now,
    () =>
      authorizeReattach(
        {
          capabilityRaw: ctx.capabilityRaw,
          expectedAud: ctx.expectedAud,
          requestedHostId: ctx.requestedHostId,
          requiredRight: ctx.requiredRight,
          sessionId: ctx.sessionId,
        },
        ctx.dpop,
        deps.hosts,
        deps.sessions,
        deps.revocation,
        now,
      ),
    'reattach',
    ctx.sessionId,
  )
}
