const { recordRequest } = require('../services/monitoringService');

/**
 * Middleware to track request metrics
 */
function metricsMiddleware(req, res, next) {
  const startTime = Date.now();

  // Store original end function
  const originalEnd = res.end;

  // Override end function to capture metrics
  res.end = function (...args) {
    const responseTime = Date.now() - startTime;
    const endpoint = `${req.method} ${req.route?.path || req.path}`;

    // Record the request metrics
    recordRequest(endpoint, res.statusCode, responseTime);

    // Call original end function
    originalEnd.apply(res, args);
  };

  next();
}

module.exports = metricsMiddleware;
