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 full error server-side (including stack trace)
  logger.error('Neošetrená chyba', err);

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

  // Never send stack traces to the client, even in development
  const errorResponse = formatErrorResponse(err, false);

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