import { Request, Response, NextFunction } from 'express';
import helmet from 'helmet';
import rateLimit from 'express-rate-limit';
import slowDown from 'express-slow-down';

export const securityHeaders = helmet({
    crossOriginResourcePolicy: { policy: 'cross-origin' }
});

export const globalLimiter = rateLimit({
    windowMs: 15 * 60 * 1000,
    max: 300,
    standardHeaders: true,
    legacyHeaders: false,
    message: {
        status: 'error',
        message: 'Trop de requêtes. Réessayez plus tard.'
    }
});

export const authLimiter = rateLimit({
    windowMs: 10 * 60 * 1000,
    max: 30,
    standardHeaders: true,
    legacyHeaders: false,
    message: {
        status: 'error',
        message: 'Trop de tentatives d’authentification. Réessayez plus tard.'
    }
});

export const verifyCodeLimiter = rateLimit({
    windowMs: 10 * 60 * 1000,
    max: 10,
    standardHeaders: true,
    legacyHeaders: false,
    message: {
        status: 'error',
        message: 'Trop de tentatives de validation de code.'
    }
});

export const authSlowDown = slowDown({
    windowMs: 10 * 60 * 1000,
    delayAfter: 5,
    delayMs: (hits) => Math.min(1000 * (hits - 5), 10000),
    validate: { delayMs: false }
});

export const verifyCodeSlowDown = slowDown({
    windowMs: 10 * 60 * 1000,
    delayAfter: 3,
    delayMs: (hits) => Math.min(1500 * (hits - 3), 12000),
    validate: { delayMs: false }
});

export const requestTimeout = (timeoutMs: number) => {
    return (req: Request, res: Response, next: NextFunction) => {
        req.setTimeout(timeoutMs);
        res.setTimeout(timeoutMs, () => {
            if (!res.headersSent) {
                res.status(408).json({
                    status: 'error',
                    message: 'Délai de requête dépassé.'
                });
            }
        });
        next();
    };
};
