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

const URL = process.env.TRAVELPORT_UNIVERSALRECORD_SERVICE;
//const URL = process.env.TRAVELPORT_UNIVERSAL_URL;
// const URL = process.env.TRAVELPORT_HOTEL_SERVICE;
const USERNAME = process.env.TRAVELPORT_USERNAME;
const PASSWORD = process.env.TRAVELPORT_PASSWORD;

exports.modifyUniversalRecordHotel = async (data) => {
  console.log("=======================================================");
  console.log("SERVICE: UniversalRecordModifyReq (HotelAdd) - START");
  console.log("=======================================================");

  try {
    const {
      traceId,
      targetBranch,
      authorizedBy,
      providerCode,
      providerLocatorCode,
      universalLocatorCode,
      hotelReservationLocator
    } = data;

    console.log("Building SOAP XML Body...");

    // 🔥 EXACT SOAP REQUEST (MATCHING YOUR STRUCTURE)
    const soapRequest = `
<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/">
    <soapenv:Header/>
    <soapenv:Body>
        <universal:UniversalRecordModifyReq 
            AuthorizedBy="${authorizedBy}" 
            TargetBranch="${targetBranch}" 
            TraceId="${traceId}" 
            Version="2" 
            ReturnRecord="true"
            xmlns:universal="http://www.travelport.com/schema/universal_v52_0"
            xmlns:hotel="http://www.travelport.com/schema/hotel_v52_0"
            xmlns:passive="http://www.travelport.com/schema/passive_v52_0"
            xmlns:common="http://www.travelport.com/schema/common_v52_0"
            xmlns:vehicle="http://www.travelport.com/schema/vehicle_v52_0"
            xmlns:air="http://www.travelport.com/schema/air_v52_0">

            <common:BillingPointOfSaleInfo OriginApplication="uAPI"/>            

            <universal:RecordIdentifier 
                ProviderCode="${providerCode}" 
                ProviderLocatorCode="${providerLocatorCode}" 
                UniversalLocatorCode="${universalLocatorCode}"/>

            <universal:UniversalModifyCmd Key="key2">
                <universal:HotelAdd ReservationLocatorCode="${hotelReservationLocator}">
                    <hotel:AssociatedRemark>
                        <common:RemarkData>ASSOCIATED HOTEL REMARK</common:RemarkData>
                    </hotel:AssociatedRemark>
                </universal:HotelAdd>
            </universal:UniversalModifyCmd>

        </universal:UniversalRecordModifyReq>
    </soapenv:Body>
</soapenv:Envelope>`;

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

    console.log("Sending Request to Travelport URL:");
    console.log(URL);

    const response = await axios.post(URL, soapRequest, {
      headers: {
        "Content-Type": "text/xml;charset=UTF-8",
        SOAPAction: ""
      },
      auth: {
        username: USERNAME,
        password: PASSWORD
      },
      timeout: 60000
    });

    console.log("Raw SOAP Response Received:");
    console.log(response.data);

    console.log("Parsing SOAP Response to JSON...");

    const parser = new xml2js.Parser({
      explicitArray: false,
      ignoreAttrs: false
    });

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

    console.log("Converted JSON Response:");
    console.log(JSON.stringify(jsonResponse, null, 2));

    console.log("SERVICE: UniversalRecordModifyReq - SUCCESS");
    console.log("=======================================================");

    return jsonResponse;

  } catch (error) {
    console.error("❌ SERVICE ERROR:");

    if (error.response) {
      console.error("Travelport SOAP Fault:");
      console.error(error.response.data);
    } else {
      console.error(error.message);
    }

    throw new Error("UniversalRecordModify HotelAdd API Failed");
  }
};