import type { RateLimitDecision } from '../domain/security.js';

/** Sliding window rate limiter in-memory. */
export class RateLimiter {
  private readonly buckets = new Map<string, number[]>();

  constructor(
    private readonly windowMs: number = 60_000,
    private readonly maxRequests: number = 60,
  ) {}

  hit(key: string, now: number = Date.now()): RateLimitDecision {
    const cutoff = now - this.windowMs;
    const stamps = this.buckets.get(key)?.filter((t) => t > cutoff) ?? [];
    if (stamps.length >= this.maxRequests) {
      const oldest = stamps[0] ?? now;
      return {
        allowed: false,
        remaining: 0,
        retryAfterSeconds: Math.max(1, Math.ceil((oldest + this.windowMs - now) / 1000)),
      };
    }
    stamps.push(now);
    this.buckets.set(key, stamps);
    return {
      allowed: true,
      remaining: this.maxRequests - stamps.length,
      retryAfterSeconds: 0,
    };
  }
}
