import rateLimit from 'express-rate-limit';
import type { RequestHandler } from 'express';

/** express-rate-limit handlers are compatible at runtime; Express 5 typings need a narrow cast. */
function asRateLimitMiddleware(
  handler: ReturnType<typeof rateLimit>
): RequestHandler {
  return handler as unknown as RequestHandler;
}

const windowMs = parseInt(process.env.RATE_LIMIT_WINDOW_MS || '60000', 10);
const maxRequests = parseInt(process.env.RATE_LIMIT_MAX_REQUESTS || '100', 10);

export const apiRateLimiter = asRateLimitMiddleware(rateLimit({
  windowMs,
  max: maxRequests,
  message: 'Too many requests from this IP, please try again later.',
  standardHeaders: true,
  legacyHeaders: false,
}));

export const strictRateLimiter = asRateLimitMiddleware(rateLimit({
  windowMs: 60 * 1000, // 1 minute
  max: 10,
  message: 'Too many requests, please try again later.',
  standardHeaders: true,
  legacyHeaders: false,
}));

/** Stricter limit for RPC-heavy /api/v1/omnl/* (stacks with apiRateLimiter). */
const omnlWindowMs = parseInt(process.env.OMNL_RATE_LIMIT_WINDOW_MS || '60000', 10);
const omnlMax = parseInt(process.env.OMNL_RATE_LIMIT_MAX || '30', 10);

export const omnlRateLimiter = asRateLimitMiddleware(rateLimit({
  windowMs: omnlWindowMs,
  max: omnlMax,
  message: 'Too many OMNL API requests from this IP, please try again later.',
  standardHeaders: true,
  legacyHeaders: false,
}));
