export class RateLimiter {
  constructor({ requestsPerMinute = 30 } = {}) {
    this.requestsPerMinute = requestsPerMinute;
    this.windows = new Map();
    setInterval(() => {
      const cutoff = Date.now() - 120_000;
      for (const [key, stamps] of this.windows) {
        const alive = stamps.filter((t) => t > cutoff);
        if (alive.length) this.windows.set(key, alive);
        else this.windows.delete(key);
      }
    }, 60_000).unref();
  }

  allow(key) {
    const now = Date.now();
    const cutoff = now - 60_000;
    const stamps = (this.windows.get(key) ?? []).filter((t) => t > cutoff);
    if (stamps.length >= this.requestsPerMinute) {
      this.windows.set(key, stamps);
      return false;
    }
    stamps.push(now);
    this.windows.set(key, stamps);
    return true;
  }
}
