/**
 * In-memory inbound rate limiter for the WhatsApp webhook.
 *
 * Keyed by (branchId, fromE164). Uses a sliding 60-second window with a
 * conservative cap so a misbehaving customer (or a spoofed inbound flood
 * during the unsigned-grace window) cannot drain OpenAI credit or pollute
 * the conversation log. Single-instance only — fine for this app's single
 * Next.js server topology, and the cap is intentionally generous so legit
 * burst traffic (a customer sending photos + captions in quick succession)
 * still gets through.
 */

const WINDOW_MS = 60_000;
const MAX_PER_WINDOW = 30;

const buckets = new Map<string, number[]>();

function pruneOldEntries(timestamps: number[], now: number): number[] {
  const cutoff = now - WINDOW_MS;
  // Most timestamps are in order — slice from first kept entry for speed.
  let i = 0;
  while (i < timestamps.length && timestamps[i] < cutoff) i++;
  return i === 0 ? timestamps : timestamps.slice(i);
}

/**
 * Returns true when the message should be processed; false when the
 * (branch, sender) bucket is over the limit. The caller is responsible
 * for any side effects (logging the drop, etc).
 */
export function allowInbound(branchId: string, fromE164: string): boolean {
  const key = `${branchId}|${fromE164}`;
  const now = Date.now();
  const existing = buckets.get(key) || [];
  const recent = pruneOldEntries(existing, now);
  if (recent.length >= MAX_PER_WINDOW) {
    buckets.set(key, recent);
    return false;
  }
  recent.push(now);
  buckets.set(key, recent);
  return true;
}

/** For tests only. */
export function _resetRateLimitBuckets(): void {
  buckets.clear();
}
