/**
 * Simple in-memory rate limiter for public API endpoints.
 * Limits requests per IP within a sliding time window.
 */

interface RateLimitEntry {
  count: number;
  resetAt: number;
}

const store = new Map<string, RateLimitEntry>();

// Periodically clean up expired entries (every 5 minutes)
let cleanupScheduled = false;
function scheduleCleanup() {
  if (cleanupScheduled) return;
  cleanupScheduled = true;
  setInterval(() => {
    const now = Date.now();
    for (const [key, entry] of store) {
      if (now > entry.resetAt) store.delete(key);
    }
  }, 5 * 60 * 1000);
}

/**
 * Check if a request is within the rate limit.
 * @param ip - Client IP address
 * @param limit - Max requests per window (default: 10)
 * @param windowMs - Time window in ms (default: 60_000 = 1 minute)
 * @returns true if allowed, false if rate limited
 */
export function checkRateLimit(
  ip: string,
  limit: number = 10,
  windowMs: number = 60_000
): boolean {
  scheduleCleanup();

  const now = Date.now();
  const entry = store.get(ip);

  if (!entry || now > entry.resetAt) {
    store.set(ip, { count: 1, resetAt: now + windowMs });
    return true;
  }

  if (entry.count >= limit) return false;
  entry.count++;
  return true;
}

/**
 * Extract client IP from request headers.
 */
export function getClientIp(request: Request): string {
  return (
    request.headers.get("x-forwarded-for")?.split(",")[0]?.trim() ||
    request.headers.get("x-real-ip") ||
    "unknown"
  );
}
