import type { NextFunction, Request, Response } from 'express';
import { TooManyRequestsError } from '../lib/errors';

/**
 * A small in-memory limiter for the few unauthenticated routes that take
 * input from the open web (the vacancy page's enquiry form). Per process, per
 * client IP, fixed window. Enough to stop a script from filling the enquiry
 * list; a real flood is the reverse proxy's job.
 */
export function rateLimit({ windowMs, max, name }: { windowMs: number; max: number; name: string }) {
  const hits = new Map<string, { count: number; resetAt: number }>();
  // Keep the map from growing without bound on a long-lived process.
  const sweep = setInterval(() => {
    const now = Date.now();
    for (const [k, v] of hits) if (v.resetAt <= now) hits.delete(k);
  }, windowMs);
  sweep.unref();

  return (req: Request, res: Response, next: NextFunction) => {
    const ip = (req.headers['x-forwarded-for']?.toString().split(',')[0] ?? req.ip ?? 'unknown').trim();
    const key = `${name}:${ip}`;
    const now = Date.now();
    const slot = hits.get(key);
    if (!slot || slot.resetAt <= now) {
      hits.set(key, { count: 1, resetAt: now + windowMs });
      return next();
    }
    slot.count++;
    if (slot.count > max) {
      res.setHeader('Retry-After', String(Math.ceil((slot.resetAt - now) / 1000)));
      return next(new TooManyRequestsError('Too many requests from this network — try again in a little while'));
    }
    next();
  };
}
