/**
 * Rate Limiting Middleware
 * Tracks request counts per user using Redis
 */

const { getRedisClient } = require('../cache/redis');

const RATE_LIMITS = {
    free: 10,
    starter: 60,
    growth: 120,
    business: 300,
    enterprise: 1000
};

async function rateLimit(req, res, next) {
    const redis = getRedisClient();
    if (!redis) return next();

    try {
        const userId = req.user?.id || req.ip;
        const plan = req.user?.plan || 'free';
        const limit = RATE_LIMITS[plan] || RATE_LIMITS.free;
        const key = `ratelimit:${userId}`;

        const current = await redis.incr(key);
        if (current === 1) await redis.expire(key, 60);

        const ttl = await redis.ttl(key);

        res.set({
            'X-RateLimit-Limit': limit,
            'X-RateLimit-Remaining': Math.max(0, limit - current),
            'X-RateLimit-Reset': Math.floor(Date.now() / 1000) + ttl
        });

        if (current > limit) {
            return res.status(429).json({
                success: false,
                error: { code: 'RATE_LIMIT_EXCEEDED', message: `Limit: ${limit}/minute`, retry_after: ttl }
            });
        }

        next();
    } catch (error) {
        next();
    }
}

module.exports = { rateLimit };
