module.exports = async function (req, res, next) {
    // Rate limiting pour les endpoints publics sensibles
    const clientIP = req.ip || req.connection.remoteAddress;
    const endpoint = req.path;

    // Configuration du rate limiting par endpoint
    const rateLimitConfig = {
        '/api/schools/resolve': { maxRequests: 10, windowMs: 60000 }, // 10 req/min
        '/api/app/config': { maxRequests: 20, windowMs: 60000 },      // 20 req/min
        'default': { maxRequests: 100, windowMs: 60000 }              // 100 req/min
    };

    const config = rateLimitConfig[endpoint] || rateLimitConfig.default;
    const rateLimitKey = `rate_limit:${endpoint}:${clientIP}`;

    try {
        // Vérifier le rate limiting si Redis est disponible
        if (sails.redis) {
            const currentCount = await sails.redis.get(rateLimitKey);

            if (currentCount && parseInt(currentCount) >= config.maxRequests) {
                sails.log.warn(`Rate limit exceeded for ${endpoint} from IP: ${clientIP}`);

                return res.status(429).json({
                    error: 'RATE_LIMIT_EXCEEDED',
                    message: 'Trop de requêtes. Veuillez réessayer dans 1 minute.',
                    retryAfter: Math.ceil(config.windowMs / 1000)
                });
            }

            // Incrémenter le compteur
            await sails.redis.incr(rateLimitKey);
            await sails.redis.expire(rateLimitKey, config.windowMs / 1000);
        }

        // Log de la requête pour audit
        sails.log.info(`API access: ${endpoint} from IP: ${clientIP}`);

        return next();

    } catch (error) {
        sails.log.error('Error in rate limiting:', error);
        // En cas d'erreur, permettre la requête mais logger
        return next();
    }
};
