/**
 * Simple in-memory rate limiter for Next.js API routes.
 * For production, consider using Redis-backed rate limiting.
 */

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

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

export interface RateLimitOptions {
  windowMs: number; // Time window in milliseconds
  maxRequests: number; // Max requests per window
  keyGenerator?: (request: Request) => string; // Custom key generator
}

export interface RateLimitResult {
  success: boolean;
  limit: number;
  remaining: number;
  resetTime: number;
}

export function createRateLimiter(options: RateLimitOptions) {
  const { windowMs, maxRequests, keyGenerator } = options;

  return {
    check(request: Request): RateLimitResult {
      const key = keyGenerator ? keyGenerator(request) : getDefaultKey(request);
      const now = Date.now();

      // Clean up expired entries
      for (const [k, v] of rateLimitStore.entries()) {
        if (v.resetTime < now) {
          rateLimitStore.delete(k);
        }
      }

      // Get or create entry
      let entry = rateLimitStore.get(key);
      if (!entry || entry.resetTime < now) {
        entry = { count: 0, resetTime: now + windowMs };
        rateLimitStore.set(key, entry);
      }

      // Check limit
      const remaining = Math.max(0, maxRequests - entry.count);
      const success = entry.count < maxRequests;

      if (success) {
        entry.count++;
      }

      return {
        success,
        limit: maxRequests,
        remaining,
        resetTime: entry.resetTime,
      };
    },

    reset(key: string): void {
      rateLimitStore.delete(key);
    },
  };
}

function getDefaultKey(request: Request): string {
  // Use IP address as default key
  const forwarded = request.headers.get('x-forwarded-for');
  const realIp = request.headers.get('x-real-ip');
  const ip = forwarded?.split(',')[0]?.trim() || realIp || 'unknown';
  return `ratelimit:${ip}`;
}

// Pre-configured rate limiters
export const authRateLimiter = createRateLimiter({
  windowMs: 15 * 60 * 1000, // 15 minutes
  maxRequests: 5, // 5 login attempts per 15 minutes
});

export const generalRateLimiter = createRateLimiter({
  windowMs: 60 * 1000, // 1 minute
  maxRequests: 100, // 100 requests per minute
});

export const strictRateLimiter = createRateLimiter({
  windowMs: 60 * 1000, // 1 minute
  maxRequests: 20, // 20 requests per minute
});
