/**
 * Best-effort in-memory sliding window. It limits bursts per server instance; for multi-instance
 * deployments, put a shared limiter (edge firewall or KV store) in front of the form as well.
 */
const hits = new Map<string, number[]>();

export function allowRequest(key: string, limit = 5, windowMs = 10 * 60 * 1000, now = Date.now()): boolean {
  const recent = (hits.get(key) ?? []).filter((timestamp) => now - timestamp < windowMs);
  if (recent.length >= limit) {
    hits.set(key, recent);
    return false;
  }
  recent.push(now);
  hits.set(key, recent);

  if (hits.size > 5000) {
    for (const [entryKey, timestamps] of hits) {
      if (timestamps.every((timestamp) => now - timestamp >= windowMs)) hits.delete(entryKey);
    }
  }
  return true;
}
