import { Request, Response, NextFunction } from "express";
import { ApiValidationError } from "../Models/Server.Error.model";

const ipLastRequest = new Map<string, number>();

// Limpia las IPs cada hora
setInterval(() => {
    const now = Date.now();
    const timeLimit = process.env.WAP_TIME_LIMIT ? parseInt(process.env.WAP_TIME_LIMIT) : 5000;
    ipLastRequest.forEach((time, ip) => {
        if (now - time > timeLimit) ipLastRequest.delete(ip);
    });
}, 3600000);

export async function rateLimiter(
    request: Request,
    response: Response,
    next: NextFunction
): Promise<void | Response | ApiValidationError> {
    const ip = request.ip;
    const timeLimit = process.env.WAP_TIME_LIMIT ? parseInt(process.env.WAP_TIME_LIMIT) : 5000;
    const currentTime = Date.now();
    const lastRequestTime = ipLastRequest.get(ip) || 0;
    if (currentTime - lastRequestTime < timeLimit) {
        response
            .status(429)
            .json(new ApiValidationError(429, "Demasiadas solicitudes. Por favor espere!"));
        return;
    }

    ipLastRequest.set(ip, currentTime);
    next();
}
