const logger = require('../config/logger.js');
const { recordError } = require('../services/monitoringService.js');

/**
 * Global error handler middleware
 */
const errorHandler = (err, req, res, _next) => {
  // Log error
  logger.error({
    type: 'error',
    message: err.message,
    stack: err.stack,
    url: req.url,
    method: req.method,
  });

  // Record error for monitoring and alerting
  recordError(err, {
    url: req.url,
    method: req.method,
    userId: req.user?.id,
  });

  // Determine status code
  const statusCode = err.statusCode || err.status || 500;

  // Map error code to numeric code
  const errorCodeMap = {
    'VALIDATION_ERROR': 400,
    'UNAUTHORIZED': 401,
    'FORBIDDEN': 403,
    'NOT_FOUND': 404,
    'CONFLICT': 409,
    'INTERNAL_SERVER_ERROR': 500,
  };

  const numericCode = errorCodeMap[err.code] || statusCode;

  // Send error response with unified format
  res.status(statusCode).json({
    code: numericCode,
    message: err.message || 'An unexpected error occurred',
    data: null,
    ...(process.env.NODE_ENV === 'development' && { 
      error: {
        code: err.code || 'INTERNAL_SERVER_ERROR',
        stack: err.stack 
      }
    }),
  });
};

/**
 * 404 Not Found handler
 */
const notFoundHandler = (req, res) => {
  res.status(404).json({
    code: 404,
    message: `Route ${req.method} ${req.url} not found`,
    data: null,
  });
};

module.exports = {
  errorHandler,
  notFoundHandler,
};
