const logger = require('../utils/logger');

const errorLogger = (err, req, res, next) => {
  // Create a request-specific logger with request ID
  const reqLogger = logger.withRequestId(req.id);

  // Log the error with context
  const errorContext = {
    method: req.method,
    url: req.url,
    userAgent: req.get('User-Agent'),
    ip: req.ip,
    userId: req.user?.id || 'anonymous',
    body: logger.sanitize(req.body),
    params: req.params,
    query: req.query,
    statusCode: err.statusCode || 500,
    stack: err.stack,
  };

  if (err.statusCode && err.statusCode < 500) {
    // Client errors (4xx)
    reqLogger.warn(`Client error: ${err.message}`, errorContext);
  } else {
    // Server errors (5xx)
    reqLogger.error(`Server error: ${err.message}`, errorContext);
  }

  // Pass error to next middleware
  next(err);
};

module.exports = errorLogger;