import NodeCache from 'node-cache';

const cache = new NodeCache({ stdTTL: 30 }); // 30 second default TTL

export function cacheMiddleware(duration = 30) {
  return (req, res, next) => {
    if (req.method !== 'GET') {
      return next();
    }

    const key = req.originalUrl;
    const cachedResponse = cache.get(key);

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

    res.originalJson = res.json;
    res.json = (body) => {
      cache.set(key, body, duration);
      res.originalJson(body);
    };

    next();
  };
}

// Clear cache utility
export function clearCache() {
  cache.flushAll();
}

// Get cache stats
export function getCacheStats() {
  return cache.getStats();
}
