const { fetchOptionalServices, fulfillOptionalServices } = require("../services/airMerchService");
const { logInfo, logError } = require("../utils/logger");

/**
 * Controller to get optional services
 */
exports.getOptionalServices = async (req, res) => {
 // const { pnr, providerCode, carrierCode, traveler, segment, fareBasisCode } = req.body;
 const {
  pnr,
  providerCode,
  carrierCode,
  traveler,
  segment,
  fareBasisCode,
  carrierLocatorCode,
  providerLocatorCode
} = req.body;

  try {
    // Validate required fields
    if (!pnr || !providerCode || !traveler || !traveler.code || !segment || !segment.key) {
      return res.status(400).json({
        success: false,
        message: "PNR, providerCode, traveler code, or segment key missing",
      });
    }

    // Log incoming request
    logInfo("Controller: Fetch Optional Services Request Received", {
      pnr,
      providerCode,
      carrierCode,
      traveler,
      segment,
    });

    // Pass top-level fields to service (exactly what Travelport XML needs)
   const optionalServicesRsp = await fetchOptionalServices({
  pnr,
  providerCode,
  carrierCode,
  traveler,
  segment,
  fareBasisCode,
  carrierLocatorCode,
  providerLocatorCode
});

    // Log successful response
    logInfo("Controller: Optional Services Fetched Successfully", {
      pnr,
      optionalServicesCount: optionalServicesRsp?.AirMerchandisingOfferAvailabilityRsp?.OptionalServices?.length || 0,
    });

    // Return the XML response converted to JSON (or raw XML if preferred)
    res.json({ success: true, data: optionalServicesRsp });
  } catch (error) {
    logError("Controller: Error fetching optional services", { pnr, error });
    res.status(500).json({ success: false, message: error.message });
  }
};

/**
 * Controller to book/fulfill selected optional services
 */
exports.bookOptionalServices = async (req, res) => {
  const { pnr, providerCode, optionalServiceKeys, creditCard } = req.body;

  try {
    logInfo("Controller: Fulfill Optional Services Request Received", {
      pnr,
      optionalServiceKeys,
      creditCard: creditCard
        ? { type: creditCard.type, maskedNumber: `****${creditCard.number.slice(-4)}` }
        : null,
    });

    const fulfilledServices = await fulfillOptionalServices({
      pnr,
      providerCode,
      optionalServiceKeys,
      creditCard,
    });

    logInfo("Controller: Optional Services Fulfilled Successfully", {
      pnr,
      fulfilledServicesCount: fulfilledServices.length,
    });

    res.json({ success: true, data: fulfilledServices });
  } catch (error) {
    logError("Controller: Error fulfilling optional services", { pnr, error });
    res.status(500).json({ success: false, message: error.message });
  }
};
