import { LRUCache } from 'lru-cache';

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

interface RateLimiterOptions {
  windowMs: number;  // Ventana de tiempo en ms
  maxRequests: number; // Máx peticiones por ventana
}

function createRateLimiter(options: RateLimiterOptions) {
  const cache = new LRUCache<string, RateLimitEntry>({
    max: 10000, // máx 10k IPs en memoria
    ttl: options.windowMs,
  });

  return {
    check(key: string): { success: boolean; remaining: number; resetAt: number } {
      const now = Date.now();
      const resetAt = now + options.windowMs;

      const entry = cache.get(key);

      if (!entry) {
        cache.set(key, { count: 1, resetAt });
        return { success: true, remaining: options.maxRequests - 1, resetAt };
      }

      if (entry.count >= options.maxRequests) {
        return { success: false, remaining: 0, resetAt: entry.resetAt };
      }

      entry.count += 1;
      cache.set(key, entry);
      return {
        success: true,
        remaining: options.maxRequests - entry.count,
        resetAt: entry.resetAt,
      };
    },
  };
}

// ─── LIMITADORES ──────────────────────────────────────────────────────────────

/** Login: max 5 intentos por minuto por IP */
export const authLimiter = createRateLimiter({ windowMs: 60_000, maxRequests: 5 });

/** API general: max 120 peticiones por minuto por usuario/IP */
export const apiLimiter = createRateLimiter({ windowMs: 60_000, maxRequests: 120 });

/** Endpoints sensibles (dispense, invoice): max 30 por minuto */
export const strictLimiter = createRateLimiter({ windowMs: 60_000, maxRequests: 30 });
