/**
 * Best-effort, in-memory rate limiting and duplicate-submission guard.
 *
 * No database or Redis is configured in this project, so this is process-local:
 * it resets on cold start and is NOT shared across multiple serverless instances.
 * It stops accidental double-submits and casual abuse from a single instance —
 * it is not a substitute for a real distributed limiter (e.g. Upstash Redis)
 * once this app is under real production load.
 */

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

function prune(timestamps: number[], windowMs: number, now: number): number[] {
  return timestamps.filter((t) => now - t < windowMs);
}

/** Returns true if `key` (typically an IP address) has exceeded `max` requests within `windowMs`. */
export function isRateLimited(key: string, max = 5, windowMs = 10 * 60 * 1000): boolean {
  const now = Date.now();
  const timestamps = prune(hits.get(key) ?? [], windowMs, now);
  timestamps.push(now);
  hits.set(key, timestamps);
  return timestamps.length > max;
}

/** Returns true if an identical (formType, dedupeKey) pair was submitted within the last `windowMs` — guards against double-click resubmits. */
export function isDuplicateSubmission(formType: string, dedupeKey: string, windowMs = 60 * 1000): boolean {
  const now = Date.now();
  const compositeKey = `${formType}:${dedupeKey}`;
  const last = recentSubmissions.get(compositeKey);

  if (last && now - last < windowMs) return true;

  recentSubmissions.set(compositeKey, now);
  return false;
}
