"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.cacheMiddleware = void 0;
const redis_1 = require("../config/redis");
const logger_1 = require("../config/logger");
const cacheMiddleware = (ttlSeconds = 300) => {
    return async (req, res, next) => {
        // Only cache GET requests
        if (req.method !== 'GET') {
            return next();
        }
        const redis = (0, redis_1.getRedisClient)();
        if (!redis || !redis.isOpen) {
            return next();
        }
        const cacheKey = `cache:${req.originalUrl || req.url}`;
        try {
            const cachedData = await redis.get(cacheKey);
            if (cachedData) {
                logger_1.logger.info(`[Redis Cache HIT] Key: ${cacheKey}`);
                res.setHeader('X-Cache', 'HIT');
                res.setHeader('Cache-Control', `public, max-age=${ttlSeconds}`);
                return res.status(200).json(JSON.parse(cachedData));
            }
            logger_1.logger.info(`[Redis Cache MISS] Key: ${cacheKey}`);
            res.setHeader('X-Cache', 'MISS');
            // Override res.json to capture response and store in Redis
            const originalJson = res.json.bind(res);
            res.json = (body) => {
                if (res.statusCode === 200 && body && body.success) {
                    redis.setEx(cacheKey, ttlSeconds, JSON.stringify(body)).catch((err) => {
                        logger_1.logger.error('Redis SetEx Error:', err);
                    });
                }
                return originalJson(body);
            };
            next();
        }
        catch (error) {
            logger_1.logger.error('Cache Middleware Error:', error);
            next();
        }
    };
};
exports.cacheMiddleware = cacheMiddleware;
//# sourceMappingURL=cache.middleware.js.map