// Per-IP exponential backoff for /auth/login. Single-instance — fine for
// Dragonflight's deployment shape (one mam-api per node). Documented limitation.
const failures = new Map(); // ip -> count

const STEPS = [1000, 2000, 4000, 8000, 16000, 30000];
const MAX_ENTRIES = 10000;  // bounded to prevent unbounded growth under spray attacks

export const ipBackoff = {
  delayMs(ip) {
    const n = failures.get(ip) || 0;
    if (n === 0) return 0;
    return STEPS[Math.min(n - 1, STEPS.length - 1)];
  },
  recordFailure(ip) {
    // Evict the oldest entry if we're at the cap. Map preserves insertion order,
    // so .keys().next().value is the oldest.
    if (failures.size >= MAX_ENTRIES && !failures.has(ip)) {
      failures.delete(failures.keys().next().value);
    }
    failures.set(ip, (failures.get(ip) || 0) + 1);
  },
  recordSuccess(ip) { failures.delete(ip); },
  reset(ip)         { failures.delete(ip); },
};
