"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.rateLimit = void 0;
const apiResponse_js_1 = require("../utils/apiResponse.js");
const buckets = new Map();
const rateLimit = ({ windowMs, max, keyPrefix }) => {
    return (req, res, next) => {
        const ip = req.ip || req.socket.remoteAddress || "unknown";
        const key = `${keyPrefix}:${ip}`;
        const now = Date.now();
        const existing = buckets.get(key);
        if (!existing || existing.resetAt <= now) {
            buckets.set(key, { count: 1, resetAt: now + windowMs });
            return next();
        }
        existing.count += 1;
        if (existing.count > max) {
            const retryAfterSeconds = Math.ceil((existing.resetAt - now) / 1000);
            res.setHeader("Retry-After", retryAfterSeconds.toString());
            return (0, apiResponse_js_1.sendError)(res, 429, "RATE_LIMITED", "Too many requests. Please try again later.");
        }
        next();
    };
};
exports.rateLimit = rateLimit;
//# sourceMappingURL=rateLimit.js.map