const Redis = require('ioredis');
const logger = require('./logger');

const redisClient = new Redis(process.env.REDIS_URL, {
  enableOfflineQueue: false,
  retryStrategy: (times) => Math.min(times * 50, 2000)
});

const cache = async (req, res, next) => {
  if (req.method !== 'GET') return next();

  try {
    const key = `cache:${req.originalUrl}`;
    const cachedResponse = await redisClient.get(key);

    if (cachedResponse) {
      return res.json(JSON.parse(cachedResponse));
    }

    res.originalJson = res.json;
    res.json = function(body) {
      redisClient.setex(
        key,
        process.env.CACHE_TTL || 3600,
        JSON.stringify(body)
      );
      res.originalJson.call(this, body);
    };

    next();
  } catch (error) {
    logger.error('Cache error:', error);
    next();
  }
};

module.exports = { cache, redisClient };