// src/middleware/rateLimit.js
// A tiny in-memory rate limiter (no Redis needed) — fine for a low/medium
// traffic NGO site on shared hosting. Resets per window per IP+route.
const buckets = new Map();

function rateLimit({ windowMs = 60_000, max = 8 } = {}) {
  return function (req, res, next) {
    const key = `${req.ip}:${req.baseUrl}${req.path}`;
    const now = Date.now();
    const entry = buckets.get(key) || { count: 0, resetAt: now + windowMs };
    if (now > entry.resetAt) {
      entry.count = 0;
      entry.resetAt = now + windowMs;
    }
    entry.count += 1;
    buckets.set(key, entry);
    if (entry.count > max) {
      const retryAfter = Math.ceil((entry.resetAt - now) / 1000);
      res.set('Retry-After', String(retryAfter));
      return res.status(429).json({ error: 'Too many requests. Please try again shortly.' });
    }
    next();
  };
}

module.exports = rateLimit;
