import { formatErrorResponse } from '../../utils/errors.js';
import { logger } from '../../utils/logger.js';

export function errorHandler(err, req, res, next) {
  // Log error
  logger.error('Unhandled error', err);

  // Get status code
  const statusCode = err.statusCode || res.statusCode !== 200 ? res.statusCode : 500;

  // Format error response
  const errorResponse = formatErrorResponse(err, process.env.NODE_ENV === 'development');

  res.status(statusCode).json(errorResponse);
}
