/**
 * In-memory MFA challenge store — temporary tokens for the login MFA flow.
 *
 * When a user with MFA enabled logs in, they get a challenge token instead of
 * access/refresh tokens. They must verify the TOTP code with this challenge token
 * within 5 minutes.
 */

interface MfaChallenge {
  userId: string;
  productId: string;
  email: string;
  role: string;
  plan: string;
  createdAt: number;
}

const CHALLENGE_TTL_MS = 5 * 60 * 1000; // 5 minutes
const challenges = new Map<string, MfaChallenge>();

// Periodic cleanup (every 60s)
setInterval(() => {
  const now = Date.now();
  for (const [token, challenge] of challenges) {
    if (now - challenge.createdAt > CHALLENGE_TTL_MS) {
      challenges.delete(token);
    }
  }
}, 60_000).unref();

export function createChallenge(data: Omit<MfaChallenge, 'createdAt'>): string {
  const token = `mfa_${crypto.randomUUID()}`;
  challenges.set(token, { ...data, createdAt: Date.now() });
  return token;
}

export function consumeChallenge(token: string): MfaChallenge | null {
  const challenge = challenges.get(token);
  if (!challenge) return null;

  // Check TTL
  if (Date.now() - challenge.createdAt > CHALLENGE_TTL_MS) {
    challenges.delete(token);
    return null;
  }

  challenges.delete(token);
  return challenge;
}

/** @internal — for testing */
export function _clearChallenges(): void {
  challenges.clear();
}
