// src/middleware/errorHandler.js

function errorHandler(err, req, res, next) {
  console.error('[ErrorHandler]', err.message || err);

  // Axios/HTTP errors from Travelport
  if (err.response) {
    const status = err.response.status || 502;
    return res.status(status).json({
      success: false,
      message: 'Travelport API error',
      travelportStatus: status,
      travelportError: err.response.data || null,
    });
  }

  // Network / timeout errors
  if (err.request) {
    return res.status(504).json({
      success: false,
      message: 'No response received from Travelport (timeout or network error)',
    });
  }

  // Generic server error
  return res.status(500).json({
    success: false,
    message: err.message || 'Internal server error',
  });
}

module.exports = errorHandler;
