const { getFlightOrder, cancelFlightOrder } = require('../models/flightOrderManagementModel');

// GET flight order
exports.getFlightOrder = async (req, res) => {
  try {
    const flightOrderId = req.params.id;
    const data = await getFlightOrder(flightOrderId);
    res.status(200).json(data);
  } catch (error) {
    console.error('Error fetching flight order:', error);

    // Extract relevant info if it's an Amadeus error
    if (error.response && error.response.body) {
     
        const errBody = JSON.parse(error.response.body);
        const apiError = errBody.errors?.[0];

        return res.status(apiError.status || 500).json({
          success: false,
          error: {
            code: apiError.code,
            title: apiError.title,
            detail: apiError.detail,
          },
        });
      } else {
      
        return res.status(500).json({
          success: false,
          message: 'An unexpected error occurred',
        });
      }
    }
  }

    


// DELETE flight order
exports.cancelFlightOrder = async (req, res) => {
  try {
    const flightOrderId = req.params.id;
    const message = await cancelFlightOrder(flightOrderId);
    res.status(204).json({ message });
  } catch (error) {
    console.error('Error cancelling flight order:', error);

     // Extract relevant info if it's an Amadeus error
    if (error.response && error.response.body) {
     
        const errBody = JSON.parse(error.response.body);
        const apiError = errBody.errors?.[0];

        return res.status(apiError.status || 500).json({
          success: false,
          error: {
            code: apiError.code,
            title: apiError.title,
            detail: apiError.detail,
          },
        });
      } else {   
    const status = error.response?.status || 500;
    const message = error.response?.data || { error: 'Server Error' };
    res.status(status).json(message);
  }
}
};

