import rateLimit from 'express-rate-limit';
import { env } from '../config/env';
import { sendError } from '../utils/helpers';

export function createRateLimiter(options?: {
  windowMs?: number;
  max?: number;
  message?: string;
}) {
  return rateLimit({
    windowMs: options?.windowMs ?? env.RATE_LIMIT_WINDOW_MS,
    max: options?.max ?? env.RATE_LIMIT_MAX,
    standardHeaders: true,
    legacyHeaders: false,
    message: {
      success: false,
      message: options?.message ?? 'Too many requests, please try again later',
    },
    // @ts-expect-error handler override for consistent response shape
    handler: (req, res) => {
      sendError(
        res,
        options?.message ?? 'Too many requests, please try again later',
        429
      );
    },
  });
}

export const globalRateLimiter = createRateLimiter();

export const authRateLimiter = createRateLimiter({
  windowMs: 15 * 60 * 1000,
  max: 10,
  message: 'Too many authentication attempts, please try again later',
});

export const uploadRateLimiter = createRateLimiter({
  windowMs: 60 * 1000,
  max: 20,
  message: 'Too many uploads, please slow down',
});
