export class CircuitBreaker {
  private failures = 0;
  private openedAt = 0;

  constructor(
    private readonly threshold = 5,
    private readonly resetMs = 10_000
  ) {}

  async run<T>(fn: () => Promise<T>): Promise<T> {
    if (this.isOpen()) throw new Error("Circuit breaker is open");
    try {
      const value = await fn();
      this.failures = 0;
      return value;
    } catch (error) {
      this.failures += 1;
      if (this.failures >= this.threshold) this.openedAt = Date.now();
      throw error;
    }
  }

  private isOpen(): boolean {
    if (this.openedAt === 0) return false;
    if (Date.now() - this.openedAt > this.resetMs) {
      this.failures = 0;
      this.openedAt = 0;
      return false;
    }
    return true;
  }
}
