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

export function errorHandler(err, req, res, next) {
  if (res.headersSent) {
    return next(err);
  }

  // Log error
  logger.error('Neošetrená chyba', err);

  // Get status code
  const statusCode = typeof err.statusCode === 'number'
    ? err.statusCode
    : res.statusCode >= 400
      ? res.statusCode
      : 500;

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

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