type Key = string;

const bucket: Map<Key, number[]> = new Map();

export function getClientKey(req: Request, extra?: string): string {
  const ip = req.headers.get("x-forwarded-for")?.split(",")[0]?.trim() || "local";
  return extra ? `${ip}:${extra}` : ip;
}

export function isRateLimited(key: string, max: number, windowMs: number): boolean {
  const now = Date.now();
  const windowStart = now - windowMs;
  const arr = bucket.get(key)?.filter((t) => t >= windowStart) ?? [];
  if (arr.length >= max) {
    bucket.set(key, arr); // cleanup
    return true;
  }
  arr.push(now);
  bucket.set(key, arr);
  return false;
}


