// Rate limiting middleware
const config = require('../config/environment');
const { auditLog } = require('../utils/logging');

// Simple in-memory rate limiting
const rateLimitStore = new Map();

// Clean up old entries periodically
setInterval(() => {
    const now = Date.now();
    for (const [key, data] of rateLimitStore.entries()) {
        if (now - data.windowStart > config.RATE_LIMIT_WINDOW_MS) {
            rateLimitStore.delete(key);
        }
    }
}, 60000); // Clean up every minute

const rateLimit = (maxRequests = null, windowMs = null) => {
    const limit = maxRequests || config.RATE_LIMIT_MAX_REQUESTS;
    const window = windowMs || config.RATE_LIMIT_WINDOW_MS;
    
    return (req, res, next) => {
        const key = req.ip;
        const now = Date.now();
        
        let rateLimitData = rateLimitStore.get(key);
        
        if (!rateLimitData || now - rateLimitData.windowStart > window) {
            rateLimitData = {
                count: 0,
                windowStart: now
            };
        }
        
        rateLimitData.count++;
        rateLimitStore.set(key, rateLimitData);
        
        if (rateLimitData.count > limit) {
            auditLog('RATE_LIMIT_EXCEEDED', {
                ip: req.ip,
                count: rateLimitData.count,
                limit: limit,
                windowMs: window
            }, req);
            
            return res.status(429).json({
                success: false,
                message: 'Too many requests. Please try again later.',
                requestId: req.requestId
            });
        }
        
        // Add rate limit headers
        res.set({
            'X-RateLimit-Limit': limit,
            'X-RateLimit-Remaining': Math.max(0, limit - rateLimitData.count),
            'X-RateLimit-Reset': new Date(rateLimitData.windowStart + window).toISOString()
        });
        
        next();
    };
};

module.exports = rateLimit;
