/**
 * MFA secrets at rest: envelope encryption with KEK_BASE64 when set.
 * Legacy plaintext values are still readable (decrypt falls back).
 */

import { encryptString, decryptString } from './envelope.js';

export function loadMfaKek(): Buffer | null {
  const b64 = process.env['KEK_BASE64'];
  if (!b64) return null;
  return Buffer.from(b64, 'base64');
}

export function sealMfaSecret(plain: string): string {
  const kek = loadMfaKek();
  if (!kek) {
    if (process.env['NODE_ENV'] === 'production') {
      throw new Error('KEK_BASE64 is required for MFA in production');
    }
    return plain;
  }
  return encryptString(plain, kek);
}

export function openMfaSecret(stored: string | null): string | null {
  if (!stored) return null;
  const kek = loadMfaKek();
  if (!kek) return stored;
  try {
    return decryptString(stored, kek);
  } catch {
    return stored;
  }
}

export function sealBackupCodes(codes: string[]): string[] {
  const kek = loadMfaKek();
  if (!kek) {
    if (process.env['NODE_ENV'] === 'production') {
      throw new Error('KEK_BASE64 is required for MFA backup codes in production');
    }
    return codes;
  }
  return [encryptString(JSON.stringify(codes), kek)];
}

export function openBackupCodes(stored: string[]): string[] {
  if (!stored.length) return [];
  const kek = loadMfaKek();
  if (!kek) return stored;
  if (stored.length === 1) {
    const first = stored[0];
    if (first === undefined) return stored;
    try {
      const json = decryptString(first, kek);
      return JSON.parse(json) as string[];
    } catch {
      return stored;
    }
  }
  return stored;
}
