const buckets = new Map();

const sweep = setInterval(() => {
  const now = Date.now();
  for (const [key, bucket] of buckets) {
    if (now - bucket.start > bucket.windowMs) buckets.delete(key);
  }
}, 60 * 1000);
if (sweep.unref) sweep.unref();

export const rateLimit = ({ windowMs = 15 * 60 * 1000, max = 100, message = 'Too many requests. Please try again later.' } = {}) => {
  return (req, res, next) => {
    const key = `${req.ip || req.connection?.remoteAddress || 'unknown'}:${req.route?.path || req.path}`;
    const now = Date.now();
    let bucket = buckets.get(key);
    if (!bucket || now - bucket.start > windowMs) {
      bucket = { start: now, windowMs, count: 0 };
      buckets.set(key, bucket);
    }
    bucket.count += 1;
    if (bucket.count > max) {
      return res.status(429).json({
        success: false,
        message,
        errors: ['Rate limit exceeded'],
      });
    }
    next();
  };
};
