interface BreakerEntry {
  failures: number;
  lastFailure: number;
  cooldownUntil: number;
}

const breakers = new Map<string, BreakerEntry>();
const THRESHOLD = 3;
const COOLDOWN_MS = 30_000;
const WINDOW_MS = 60_000;

export function recordFailure(compositeId: string): void {
  const now = Date.now();
  const entry = breakers.get(compositeId);
  if (!entry || now - entry.lastFailure > WINDOW_MS) {
    breakers.set(compositeId, { failures: 1, lastFailure: now, cooldownUntil: 0 });
    return;
  }
  entry.failures++;
  entry.lastFailure = now;
  if (entry.failures >= THRESHOLD) {
    entry.cooldownUntil = now + COOLDOWN_MS;
  }
}

export function recordSuccess(compositeId: string): void {
  breakers.delete(compositeId);
}

export function isTripped(compositeId: string): boolean {
  const entry = breakers.get(compositeId);
  if (!entry) return false;
  if (entry.cooldownUntil === 0) return false;
  if (Date.now() > entry.cooldownUntil) {
    breakers.delete(compositeId);
    return false;
  }
  return true;
}
