const logger = require('../utils/logger');
const { CustomError } = require('../utils/errors');

const errorHandler = (err, req, res, next) => {
  const correlationId = req.correlationId;

  logger.error('Error occurred', {
    error: {
      message: err.message,
      stack: process.env.NODE_ENV === 'development' ? err.stack : undefined,
      name: err.name,
      code: err.code
    },
    correlationId,
    path: req.path,
    method: req.method,
    body: req.body,
    params: req.params,
    query: req.query,
    user: req.user?.id
  });

  if (err instanceof CustomError) {
    return res.status(err.statusCode).json({
      status: 'error',
      message: err.message,
      code: err.code,
      correlationId
    });
  }

  // Handle specific error types
  if (err.name === 'SequelizeValidationError') {
    return res.status(400).json({
      status: 'error',
      message: 'Validation error',
      errors: err.errors.map(e => ({ field: e.path, message: e.message })),
      correlationId
    });
  }

  if (err.name === 'SequelizeUniqueConstraintError') {
    return res.status(409).json({
      status: 'error',
      message: 'Resource already exists',
      correlationId
    });
  }

  // Default error
  const statusCode = err.statusCode || 500;
  const message = statusCode === 500 ? 'Internal server error' : err.message;

  return res.status(statusCode).json({
    status: 'error',
    message,
    correlationId,
    ...(process.env.NODE_ENV === 'development' && { stack: err.stack })
  });
};