// Rate limiting utility
// Uses in-memory storage for simplicity - should use Redis in production

interface RateLimitResult {
  success: boolean;
  remaining: number;
  reset: Date;
}

const store = new Map<string, { count: number; reset: Date }>();

export function getClientIp(request: Request): string {
  const forwarded = request.headers.get("x-forwarded-for");
  if (forwarded) {
    return forwarded.split(",")[0].trim();
  }
  return request.headers.get("x-real-ip") || "unknown";
}

export async function rateLimit(
  identifier: string,
  opts: { max: number; windowSec: number }
): Promise<RateLimitResult> {
  const key = identifier;
  const now = new Date();
  const windowMs = opts.windowSec * 1000;

  const record = store.get(key);

  if (!record || record.reset.getTime() < now.getTime()) {
    // New window
    const reset = new Date(now.getTime() + windowMs);
    store.set(key, { count: 1, reset });
    return {
      success: true,
      remaining: opts.max - 1,
      reset,
    };
  }

  if (record.count >= opts.max) {
    // Rate limited
    return {
      success: false,
      remaining: 0,
      reset: record.reset,
    };
  }

  // Increment count
  record.count++;
  store.set(key, record);

  return {
    success: true,
    remaining: opts.max - record.count,
    reset: record.reset,
  };
}

// Helper to get rate limit key for an endpoint
export function getRateLimitKey(endpoint: string, identifier: string): string {
  return `ratelimit:${endpoint}:${identifier}`;
}