const logger = require('../utils/logger');
const { redis } = require('../config/services');
const { ensureRedisConnection } = require('../services/cacheService');

const logRedisStats = async () => {
  try {
    if (!redis) {
      logger.warn('Redis baglantisi bulunamadigi icin kayit sayisi alinamadi');
      return;
    }
    await ensureRedisConnection();
    const count = await redis.dbsize();
    logger.info(`📊 Redis kayit sayisi: ${count}`);
  } catch (error) {
    logger.warn(`Redis kayit sayisi alinamadi: ${error.message}`);
  }
};

module.exports = (req, res, next) => {
  const start = process.hrtime.bigint();

  res.on('finish', () => {
    const diff = process.hrtime.bigint() - start;
    const durationMs = Number(diff) / 1e6;
    const cacheHit = res.locals.cacheHit;
    logger.request({
      method: req.method,
      url: req.originalUrl,
      status: res.statusCode,
      durationMs,
      cacheHit
    });
    logRedisStats();
  });

  next();
};
