/**
 * Reads + validates the MFA-related env vars at boot.
 *
 *   MFA_FRESHNESS_SECONDS — default 600 (10 min). Window during
 *     which a session's `mfaVerifiedAt` is considered "fresh enough"
 *     for routes decorated with `@RequireMfa()`. The decorator can
 *     override it per-route; the env value is the global default.
 *
 * Minimum: 60 s. Anything below would mean the user has to re-MFA
 * basically on every navigation; the floor catches a misconfigured
 * `MFA_FRESHNESS_SECONDS=30` before the BFF starts. ADR-0011's
 * confirmation list explicitly calls out this floor.
 *
 * No upper bound — operators can pick a long window for low-risk
 * surfaces if they want; the trade-off is theirs to record in their
 * runbook, not the BFF's to refuse.
 */
const DEFAULT_FRESHNESS_SECONDS = 600;
const MIN_FRESHNESS_SECONDS = 60;

export interface MfaConfig {
  readonly freshnessSeconds: number;
}

export function readMfaConfig(): MfaConfig {
  const raw = process.env['MFA_FRESHNESS_SECONDS'];
  if (raw === undefined || raw === '') {
    return { freshnessSeconds: DEFAULT_FRESHNESS_SECONDS };
  }
  const value = Number(raw);
  if (!Number.isInteger(value) || value <= 0) {
    throw new Error(`MFA_FRESHNESS_SECONDS must be a positive integer (got "${raw}").`);
  }
  if (value < MIN_FRESHNESS_SECONDS) {
    throw new Error(
      `MFA_FRESHNESS_SECONDS must be ≥ ${MIN_FRESHNESS_SECONDS} (got ${value}). ` +
        `Anything shorter forces re-MFA on every navigation and is almost certainly a misconfiguration.`,
    );
  }
  return { freshnessSeconds: value };
}
