export type RateLimitCheckResult = {
  allowed: boolean;
  retryAfterSeconds: number;
  remaining: number;
};

type RateLimiterOptions = {
  limit: number;
  windowMs: number;
  now?: () => number;
};

export class RateLimiterService {
  private readonly limit: number;
  private readonly windowMs: number;
  private readonly now: () => number;
  private readonly requestsByKey = new Map<string, number[]>();

  constructor(options: RateLimiterOptions) {
    this.limit = options.limit;
    this.windowMs = options.windowMs;
    this.now = options.now ?? (() => Date.now());
  }

  check(key: string): RateLimitCheckResult {
    const normalizedKey = key.trim().toLowerCase();
    if (!normalizedKey) {
      return {
        allowed: false,
        retryAfterSeconds: Math.ceil(this.windowMs / 1000),
        remaining: 0,
      };
    }

    const nowMs = this.now();
    const windowStart = nowMs - this.windowMs;
    const timestamps = this.requestsByKey.get(normalizedKey) ?? [];
    const recent = timestamps.filter((stamp) => stamp > windowStart);

    if (recent.length >= this.limit) {
      const oldestInWindow = recent[0] ?? nowMs;
      const retryAfterMs = Math.max(0, oldestInWindow + this.windowMs - nowMs);

      this.requestsByKey.set(normalizedKey, recent);

      return {
        allowed: false,
        retryAfterSeconds: Math.max(1, Math.ceil(retryAfterMs / 1000)),
        remaining: 0,
      };
    }

    recent.push(nowMs);
    this.requestsByKey.set(normalizedKey, recent);

    return {
      allowed: true,
      retryAfterSeconds: 0,
      remaining: Math.max(0, this.limit - recent.length),
    };
  }
}
