/**
 * API性能监控中间件
 * @file performance-middleware.js
 * @description 用于监控API请求性能的Express中间件
 */
const { performanceMonitor, events: perfEvents } = require('../utils/performance-monitor');
const logger = require('../utils/logger');

/**
 * API性能监控中间件
 * 记录请求的响应时间、状态码和错误率
 */
function apiPerformanceMonitor(req, res, next) {
  // 记录请求开始时间
  const startTime = Date.now();
  const originalUrl = req.originalUrl || req.url;
  const method = req.method;
  
  // 为了捕获响应信息，我们需要拦截res.end
  const originalEnd = res.end;
  res.end = function(chunk, encoding) {
    // 恢复原始的end方法
    res.end = originalEnd;
    
    // 计算响应时间
    const duration = Date.now() - startTime;
    
    // 获取状态码
    const statusCode = res.statusCode;
    
    // 记录请求信息
    const requestInfo = {
      method,
      path: originalUrl,
      statusCode,
      duration,
      timestamp: new Date(),
      userAgent: req.headers['user-agent'],
      ip: req.ip || req.connection.remoteAddress
    };
    
    // 记录到性能监控系统
    performanceMonitor.recordApiRequest(req, res, startTime);
    
    // 记录慢响应
    const slowThreshold = performanceMonitor.getAlertThresholds().api.responseTime;
    if (duration > slowThreshold) {
      logger.warn(`慢API响应: ${method} ${originalUrl} - ${duration}ms (阈值: ${slowThreshold}ms)`);
    }
    
    // 记录错误响应
    if (statusCode >= 400) {
      logger.error(`API错误: ${method} ${originalUrl} - 状态码 ${statusCode}`);
    }
    
    // 调用原始的end方法
    return originalEnd.call(this, chunk, encoding);
  };
  
  // 继续处理请求
  next();
}

/**
 * 错误处理中间件
 * 捕获并记录API错误
 */
function apiErrorMonitor(err, req, res, next) {
  // 记录错误信息
  logger.error(`API错误: ${req.method} ${req.originalUrl || req.url}`, {
    error: err.message,
    stack: err.stack
  });
  
  // 触发错误事件
  perfEvents.emit('apiError', {
    method: req.method,
    path: req.originalUrl || req.url,
    error: err.message,
    timestamp: new Date()
  });
  
  // 继续错误处理链
  next(err);
}

module.exports = {
  apiPerformanceMonitor,
  apiErrorMonitor
};