/**
 * Simple in-memory rate limiter for Server Actions.
 * Tracks requests per IP within a sliding time window.
 * Automatically clears stale entries to prevent memory leaks.
 */

const WINDOW_MS = 60_000; // 1 minute
const MAX_REQUESTS_PER_WINDOW = 30; // per IP per minute
const CLEANUP_INTERVAL_MS = 5 * 60_000; // clean stale entries every 5 minutes

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

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

// Periodically clean up expired entries to prevent memory growth
if (typeof setInterval !== 'undefined') {
  setInterval(() => {
    const now = Date.now();
    for (const [key, entry] of ipMap.entries()) {
      if (now > entry.resetAt) {
        ipMap.delete(key);
      }
    }
  }, CLEANUP_INTERVAL_MS);
}

/**
 * Returns true if the request is allowed, false if rate limit exceeded.
 * @param ip - The client IP address (use 'unknown' if not available)
 * @param scope - Optional scope to namespace limits (e.g. 'purchase', 'sales')
 */
export function checkRateLimit(ip: string, scope = 'default'): boolean {
  const key = `${scope}:${ip}`;
  const now = Date.now();
  const entry = ipMap.get(key);

  if (!entry || now > entry.resetAt) {
    ipMap.set(key, { count: 1, resetAt: now + WINDOW_MS });
    return true;
  }

  if (entry.count >= MAX_REQUESTS_PER_WINDOW) {
    return false;
  }

  entry.count++;
  return true;
}
