/**
 * In-process sliding-window rate limiter keyed by an arbitrary client bucket (per-IP for /login).
 * Mirrors the base app's control-plane auth-login limiter: a rejected attempt is NOT recorded, so a
 * throttled client can't push its own window forward. Pure/injectable clock for tests.
 */
export interface RateLimiter {
  /** Returns true and records the hit if under the limit; false (no record) when the window is full. */
  allow(key: string): boolean
}

/** Default per-IP login attempts within the window. */
export const DEFAULT_LOGIN_RATE_MAX = 10
/** Default login rate window (ms): 15 minutes. */
export const DEFAULT_LOGIN_RATE_WINDOW_MS = 15 * 60 * 1000

export function createSlidingWindowLimiter(max: number, windowMs: number, now: () => number): RateLimiter {
  const hits = new Map<string, number[]>()
  return {
    allow(key: string): boolean {
      const ts = now()
      const cutoff = ts - windowMs
      const kept = (hits.get(key) ?? []).filter((t) => t > cutoff)
      if (kept.length >= max) {
        hits.set(key, kept) // persist the pruned window; do NOT record this rejected attempt
        return false
      }
      kept.push(ts)
      hits.set(key, kept)
      return true
    },
  }
}
