/**
 * Tiny in-memory rate limiter. Suitable for single-instance dev and small
 * production deployments. For multi-instance production, swap to Redis.
 *
 * Default: 10 attempts per IP per 60s window, sliding count.
 */

type Bucket = { count: number; resetAt: number };
const buckets = new Map<string, Bucket>();

const WINDOW_MS = 60_000;
const MAX_PER_WINDOW = 10;

export function rateLimit(ip: string): { allowed: boolean; remaining: number; resetAt: number } {
  const now = Date.now();
  const existing = buckets.get(ip);
  if (!existing || existing.resetAt < now) {
    buckets.set(ip, { count: 1, resetAt: now + WINDOW_MS });
    return { allowed: true, remaining: MAX_PER_WINDOW - 1, resetAt: now + WINDOW_MS };
  }
  existing.count += 1;
  if (existing.count > MAX_PER_WINDOW) {
    return { allowed: false, remaining: 0, resetAt: existing.resetAt };
  }
  return { allowed: true, remaining: MAX_PER_WINDOW - existing.count, resetAt: existing.resetAt };
}

/** Best-effort IP from common Next.js / proxy headers. */
export function getClientIp(headers: Headers): string {
  return (
    headers.get("x-forwarded-for")?.split(",")[0]?.trim() ||
    headers.get("x-real-ip") ||
    "unknown"
  );
}
