/**
 * Minimal in-memory rate limiter for public form endpoints.
 *
 * NOTE: this only limits requests within a single server process/instance.
 * On serverless or multi-instance deployments it will NOT share state
 * across instances. For production, replace with a shared store
 * (e.g. Upstash Redis + @upstash/ratelimit) — this is a placeholder
 * that at least blocks naive scripted spam in a single-instance dev/staging setup.
 */
const hits = new Map<string, { count: number; resetAt: number }>();

export function rateLimit(key: string, limit = 5, windowMs = 60_000) {
  const now = Date.now();
  const entry = hits.get(key);

  if (!entry || entry.resetAt < now) {
    hits.set(key, { count: 1, resetAt: now + windowMs });
    return { ok: true };
  }

  if (entry.count >= limit) {
    return { ok: false, retryAfterMs: entry.resetAt - now };
  }

  entry.count += 1;
  return { ok: true };
}

export function getClientKey(req: Request) {
  return (
    req.headers.get('x-forwarded-for')?.split(',')[0].trim() ??
    req.headers.get('x-real-ip') ??
    'unknown'
  );
}
