// 统一错误处理中间件
const errorHandler = (err, req, res, next) => {
  // 记录错误日志
  console.error(`[${new Date().toISOString()}] Error:`, {
    message: err.message,
    stack: err.stack,
    url: req.url,
    method: req.method,
    ip: req.ip,
    userAgent: req.get('User-Agent')
  });

  // 默认错误响应
  let statusCode = 500;
  let message = '服务器内部错误';
  let code = 'INTERNAL_SERVER_ERROR';

  // 根据错误类型设置响应
  if (err.name === 'ValidationError') {
    statusCode = 400;
    message = '请求参数验证失败';
    code = 'VALIDATION_ERROR';
  } else if (err.name === 'UnauthorizedError') {
    statusCode = 401;
    message = '未授权访问';
    code = 'UNAUTHORIZED';
  } else if (err.name === 'ForbiddenError') {
    statusCode = 403;
    message = '禁止访问';
    code = 'FORBIDDEN';
  } else if (err.name === 'NotFoundError') {
    statusCode = 404;
    message = '资源未找到';
    code = 'NOT_FOUND';
  } else if (err.code === 'SQLITE_ERROR') {
    statusCode = 500;
    message = '数据库操作失败';
    code = 'DATABASE_ERROR';
  }

  // 开发环境下返回详细错误信息
  const isDevelopment = process.env.NODE_ENV === 'development';
  
  res.status(statusCode).json({
    success: false,
    message,
    code,
    ...(isDevelopment && { 
      error: err.message,
      stack: err.stack 
    })
  });
};

// 404处理中间件
const notFoundHandler = (req, res) => {
  res.status(404).json({
    success: false,
    message: '请求的资源不存在',
    code: 'NOT_FOUND',
    path: req.path,
    method: req.method
  });
};

// 请求日志中间件
const requestLogger = (req, res, next) => {
  const start = Date.now();
  
  // 记录请求开始
  console.log(`[${new Date().toISOString()}] ${req.method} ${req.url} - ${req.ip}`);
  
  // 监听响应结束
  res.on('finish', () => {
    const duration = Date.now() - start;
    console.log(`[${new Date().toISOString()}] ${req.method} ${req.url} - ${res.statusCode} - ${duration}ms`);
  });
  
  next();
};

// 性能监控中间件
const performanceMonitor = (req, res, next) => {
  const start = process.hrtime.bigint();
  
  res.on('finish', () => {
    const end = process.hrtime.bigint();
    const duration = Number(end - start) / 1000000; // 转换为毫秒
    
    // 如果响应时间超过1秒，记录警告
    if (duration > 1000) {
      console.warn(`[PERFORMANCE WARNING] ${req.method} ${req.url} took ${duration.toFixed(2)}ms`);
    }
  });
  
  next();
};

module.exports = {
  errorHandler,
  notFoundHandler,
  requestLogger,
  performanceMonitor
};