const AppError = require('../utils/appError')

const requestCache = new Map()
const WINDOW_MS = 5000

module.exports = function duplicateGuard(req, res, next) {
    const key = `${req.ip}:${req.originalUrl}:${JSON.stringify(req.body || {})}`
    const now = Date.now()
    const lastTime = requestCache.get(key)

    if (lastTime && now - lastTime < WINDOW_MS) {
        return next(new AppError('请求过于频繁，请稍后重试', 429))
    }

    requestCache.set(key, now)

    setTimeout(() => {
        requestCache.delete(key)
    }, WINDOW_MS)

    next()
}
