const axios = require("axios");
const xml2js = require("xml2js");

const URL = process.env.TRAVELPORT_SYSTEM_SERVICE;
const USERNAME = process.env.TRAVELPORT_USERNAME;
const PASSWORD = process.env.TRAVELPORT_PASSWORD;
const BRANCH = process.env.TARGET_BRANCH;
const HOTEL = process.env.TRAVELPORT_HOTEL_SERVICE


exports.searchHotelAvailability = async (data) => {
  console.log("SERVICE: HotelSearchAvailabilityReq - START");

  const {
    location,
    checkinDate,
    checkoutDate
  } = data;

  const traceId = "TRACE_" + Date.now();

  console.log("TraceId:", traceId);

  // ✅ SOAP XML BODY
  const soapBody = `
  <soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/">
    <soapenv:Header/>
    <soapenv:Body>
      <hot:HotelSearchAvailabilityReq AuthorizedBy="TEST"
        TargetBranch="${BRANCH}"
        TraceId="${traceId}"
        xmlns:hot="http://www.travelport.com/schema/hotel_v54_0"
        xmlns:com="http://www.travelport.com/schema/common_v54_0">

        <com:BillingPointOfSaleInfo OriginApplication="UAPI"/>

        <hot:HotelSearchLocation>
          <hot:HotelLocation Location="${location}"/>
        </hot:HotelSearchLocation>

       

        <hot:HotelStay>
          <hot:CheckinDate>${checkinDate}</hot:CheckinDate>
          <hot:CheckoutDate>${checkoutDate}</hot:CheckoutDate>
        </hot:HotelStay>

      </hot:HotelSearchAvailabilityReq>
    </soapenv:Body>
  </soapenv:Envelope>`;

  console.log("SOAP REQUEST:");
  console.log(soapBody);

  try {
    const response = await axios.post(HOTEL, soapBody, {
      headers: {
        "Content-Type": "text/xml;charset=UTF-8",
        SOAPAction: "HotelSearchAvailabilityReq",
        Authorization:
          "Basic " +
          Buffer.from(USERNAME + ":" + PASSWORD).toString("base64"),
      },
      timeout: 60000,
    });

    console.log("RAW SOAP RESPONSE RECEIVED");

    // ✅ XML ➜ JSON
    const parser = new xml2js.Parser({
      explicitArray: false,
      ignoreAttrs: false,
    });

    const jsonResponse = await parser.parseStringPromise(response.data);

    console.log("SERVICE: XML converted to JSON");

    return jsonResponse;

  } catch (error) {
    console.error("SERVICE ERROR:", error.response?.data || error.message);
    throw new Error("Travelport Hotel Search Failed");
  }
};