// @ts-check
const buckets = new Map();
/** 10 secondi */
const WINDOW_MS = 10_000;
const LIMIT = 100;

function rateLimit(req, res, next) {
  const key = req.ip || 'global';
  const now = Date.now();
  const bucket = buckets.get(key) || { count: 0, ts: now };
  if (now - bucket.ts > WINDOW_MS) {
    bucket.count = 0;
    bucket.ts = now;
  }
  bucket.count++;
  buckets.set(key, bucket);
  if (bucket.count > LIMIT) return res.status(429).json({ message: 'Troppo traffico, riprova tra poco.' });
  next();
}

module.exports = { rateLimit };
