/**
 * Centralized Rate Limiting Configuration for Edge Functions
 * 
 * Provides standardized rate limit tiers that can be imported by any edge function.
 * This ensures consistent rate limiting behavior across the application.
 */

import { RateLimitConfig } from './rateLimiter.ts';

/**
 * Rate Limit Tier Definitions
 * 
 * Choose the appropriate tier based on the operation cost and abuse risk:
 * 
 * - **STRICT**: For expensive operations (uploads, exports, data modifications)
 * - **MODERATE**: For standard API operations (moderation actions, content creation)
 * - **STANDARD**: For typical read/write operations (most endpoints)
 * - **LENIENT**: For lightweight read operations (cached data, public endpoints)
 * - **GENEROUS**: For high-frequency operations (polling, real-time updates)
 */

// Base time window for all rate limiters (1 minute)
const RATE_LIMIT_WINDOW_MS = 60000;

/**
 * STRICT: 5 requests per minute
 * 
 * Use for:
 * - File uploads (images, documents)
 * - Data exports
 * - Batch operations
 * - Resource-intensive computations
 * - CloudFlare API calls
 * 
 * Examples: upload-image, export-user-data
 */
export const RATE_LIMIT_STRICT: RateLimitConfig = {
  windowMs: RATE_LIMIT_WINDOW_MS,
  maxRequests: 5,
};

/**
 * MODERATE: 10 requests per minute
 * 
 * Use for:
 * - Moderation actions (approve, reject)
 * - Content submission
 * - User profile updates
 * - Email sending
 * - Notification triggers
 * 
 * Examples: process-selective-approval, process-selective-rejection, submit-entity-edit
 */
export const RATE_LIMIT_MODERATE: RateLimitConfig = {
  windowMs: RATE_LIMIT_WINDOW_MS,
  maxRequests: 10,
};

/**
 * STANDARD: 20 requests per minute
 * 
 * Use for:
 * - Standard read/write operations
 * - Search endpoints
 * - Contact forms
 * - Account management
 * - Authentication operations
 * 
 * Examples: send-contact-message, request-account-deletion, validate-email
 */
export const RATE_LIMIT_STANDARD: RateLimitConfig = {
  windowMs: RATE_LIMIT_WINDOW_MS,
  maxRequests: 20,
};

/**
 * LENIENT: 30 requests per minute
 * 
 * Use for:
 * - Lightweight read operations
 * - Cached data retrieval
 * - Public endpoint queries
 * - Status checks
 * - Location detection
 * 
 * Examples: detect-location, check-transaction-status
 */
export const RATE_LIMIT_LENIENT: RateLimitConfig = {
  windowMs: RATE_LIMIT_WINDOW_MS,
  maxRequests: 30,
};

/**
 * GENEROUS: 60 requests per minute
 * 
 * Use for:
 * - High-frequency polling
 * - Real-time updates
 * - Webhook receivers
 * - Health checks
 * - Internal service-to-service calls
 * 
 * Examples: novu-webhook, scheduled-maintenance
 */
export const RATE_LIMIT_GENEROUS: RateLimitConfig = {
  windowMs: RATE_LIMIT_WINDOW_MS,
  maxRequests: 60,
};

/**
 * PER_USER: 20 requests per minute (default)
 * 
 * Use for authenticated endpoints where you want to rate limit per user ID
 * rather than per IP address. Useful for:
 * - User-specific operations
 * - Preventing account abuse
 * - Per-user quotas
 * 
 * Can be customized with different request counts:
 * - perUserStrict: 5 req/min
 * - perUserModerate: 10 req/min
 * - perUserStandard: 20 req/min (default)
 * - perUserLenient: 40 req/min
 */
export const RATE_LIMIT_PER_USER_STRICT: RateLimitConfig = {
  windowMs: RATE_LIMIT_WINDOW_MS,
  maxRequests: 5,
  keyGenerator: (req: Request) => {
    // Extract user ID from Authorization header JWT
    const authHeader = req.headers.get('Authorization');
    if (authHeader) {
      try {
        const token = authHeader.replace('Bearer ', '');
        const payload = JSON.parse(atob(token.split('.')[1]));
        return `user:${payload.sub}`;
      } catch {
        // Fall back to IP if JWT parsing fails
        return req.headers.get('x-forwarded-for')?.split(',')[0] || '0.0.0.0';
      }
    }
    return req.headers.get('x-forwarded-for')?.split(',')[0] || '0.0.0.0';
  }
};

export const RATE_LIMIT_PER_USER_MODERATE: RateLimitConfig = {
  ...RATE_LIMIT_PER_USER_STRICT,
  maxRequests: 10,
};

export const RATE_LIMIT_PER_USER_STANDARD: RateLimitConfig = {
  ...RATE_LIMIT_PER_USER_STRICT,
  maxRequests: 20,
};

export const RATE_LIMIT_PER_USER_LENIENT: RateLimitConfig = {
  ...RATE_LIMIT_PER_USER_STRICT,
  maxRequests: 40,
};

/**
 * Rate Limit Tier Summary
 * 
 * | Tier              | Requests/Min | Use Case                          |
 * |-------------------|--------------|-----------------------------------|
 * | STRICT            | 5            | Expensive operations, uploads     |
 * | MODERATE          | 10           | Moderation, submissions           |
 * | STANDARD          | 20           | Standard read/write operations    |
 * | LENIENT           | 30           | Lightweight reads, public data    |
 * | GENEROUS          | 60           | Polling, webhooks, health checks  |
 * | PER_USER_STRICT   | 5/user       | User-specific expensive ops       |
 * | PER_USER_MODERATE | 10/user      | User-specific moderation          |
 * | PER_USER_STANDARD | 20/user      | User-specific standard ops        |
 * | PER_USER_LENIENT  | 40/user      | User-specific frequent ops        |
 */
