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

// const HOTEL_URL = process.env.TRAVELPORT_HOTEL_SERVICE;
// const USERNAME = process.env.TRAVELPORT_USERNAME;
// const PASSWORD = process.env.TRAVELPORT_PASSWORD;

// exports.createReservation = async (data) => {
//   console.log("SERVICE: HotelCreateReservation - START");

//   try {

//     const {
//       traceId,
//       targetBranch,
//       authorizedBy,
//       traveler,
//       hotelRateDetail,
//       hotelProperty,
//       stay,
//       guarantee,
//       guestInformation
//     } = data;

//     // =============================
//     // SOAP XML BODY (EXACT FORMAT)
//     // =============================

//     const soapBody = `
//     <soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/"
//       xmlns:com="http://www.travelport.com/schema/common_v54_0"
//       xmlns:univ="http://www.travelport.com/schema/universal_v54_0"
//       xmlns:hotel="http://www.travelport.com/schema/hotel_v54_0">

//       <soapenv:Header/>
//       <soapenv:Body>

//         <univ:HotelCreateReservationReq 
//           RetrieveProviderReservationDetails="true"
//           ProviderCode="1G"
//           UserAcceptance="true"
//           AuthorizedBy="${authorizedBy}"
//           TargetBranch="${targetBranch}"
//           TraceId="${traceId}">

//           <com:BillingPointOfSaleInfo OriginApplication="UAPI"/>

//           <com:BookingTraveler Key="${traveler.key}" TravelerType="ADT" VIP="true">
//             <com:BookingTravelerName 
//               Prefix="${traveler.prefix}" 
//               First="${traveler.first}" 
//               Middle="${traveler.middle}" 
//               Last="${traveler.last}"/>

//             <com:PhoneNumber Key="${traveler.phoneKey}" 
//               Location="${traveler.location}" 
//               Number="${traveler.phone}" 
//               Type="${traveler.type}"/>

//             <com:Email Type="Home" EmailID="${traveler.email}"/>

//             <com:Address Key="${traveler.addressKey}">
//               <com:AddressName>Home Address</com:AddressName>
//               <com:Street>${traveler.street1}</com:Street>
              
             
//             </com:Address>
//           </com:BookingTraveler>

//           <hotel:HotelRateDetail 
//             RatePlanType="${hotelRateDetail.ratePlanType}"
//             Base="${hotelRateDetail.base}"
//             Total="${hotelRateDetail.total}"
//             RateChangeIndicator="true"
//             ExtraFeesIncluded="false">

//             <hotel:HotelRateByDate 
//               EffectiveDate="${hotelRateDetail.effectiveDate}"
//               ExpireDate="${hotelRateDetail.expireDate}"/>

//             <hotel:Commission Indicator="true"/>
//             <hotel:CancelInfo NonRefundableStayIndicator="false"/>
//             <hotel:GuaranteeInfo GuaranteeType="Guarantee"/>
//           </hotel:HotelRateDetail>

//           <hotel:HotelProperty 
//             HotelChain="${hotelProperty.chain}"
//             HotelCode="${hotelProperty.code}"
//             HotelLocation="${hotelProperty.location}"
//             Name="${hotelProperty.name}"/>

//           <hotel:HotelStay>
//             <hotel:CheckinDate>${stay.checkin}</hotel:CheckinDate>
//             <hotel:CheckoutDate>${stay.checkout}</hotel:CheckoutDate>
//           </hotel:HotelStay>

//           <com:Guarantee Type="Deposit">
//             <com:CreditCard 
//               Type="${guarantee.type}"
//               Number="${guarantee.number}"
//               ExpDate="${guarantee.expDate}"
//               CVV="${guarantee.cvv}"/>

//           </com:Guarantee>

//           <hotel:GuestInformation NumberOfRooms="${guestInformation.rooms}">
//             <hotel:NumberOfAdults>${guestInformation.adults}</hotel:NumberOfAdults>
//           </hotel:GuestInformation>

//         </univ:HotelCreateReservationReq>

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

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

//     // =============================
//     // SOAP CALL
//     // =============================

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

//     console.log("RAW SOAP RESPONSE:");
//     console.log(response.data);

//     // =============================
//     // XML → JSON
//     // =============================

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

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

//     console.log("PARSED JSON RESPONSE:");
//     console.log(JSON.stringify(jsonResponse, null, 2));

//     console.log("SERVICE: HotelCreateReservation - SUCCESS");

//     return jsonResponse;

//   } catch (error) {
//     console.error("SERVICE: HotelCreateReservation - ERROR");

//     if (error.response) {
//       console.error("SOAP FAULT RESPONSE:");
//       console.error(error.response.data);
//     }

//     throw error;
//   }
// };


const axios  = require("axios");
const xml2js = require("xml2js");
require("dotenv").config();

const HOTEL_URL  = process.env.TRAVELPORT_HOTEL_SERVICE;
const USERNAME   = process.env.TRAVELPORT_USERNAME;
const PASSWORD   = process.env.TRAVELPORT_PASSWORD;

const TARGET_BRANCH = process.env.TARGET_BRANCH;
const AUTHORIZED_BY = process.env.AUTHORIZED_BY;
const PROVIDER      = process.env.PROVIDER_CODE || "1G";

exports.createReservation = async (data)=>{

console.log("SERVICE: HotelCreateReservation START");

try{

/* ------------------------------------------------
   META (FROM ENV ONLY)
------------------------------------------------*/

const traceId = `TRACE_${Date.now()}`;


/* ------------------------------------------------
   DESTRUCTURE PAYLOAD
------------------------------------------------*/

const {
traveler,
hotelRateDetail,
hotelProperty,
stay,
guarantee,
guestInformation,
loyaltyCard,
corporateDiscountId,
specialRequests
} = data;


/* ------------------------------------------------
   BOOKING TRAVELER XML
------------------------------------------------*/

const bookingTravelerXML = `
<com:BookingTraveler Key="${traveler.key}" TravelerType="${traveler.travelerType || "ADT"}">

<com:BookingTravelerName
First="${traveler.first}"
Last="${traveler.last}"
${traveler.middle ? `Middle="${traveler.middle}"` : ""}
${traveler.prefix ? `Prefix="${traveler.prefix}"` : ""}
/>

<com:PhoneNumber
Number="${traveler.phone}"
Type="${traveler.phoneType || "Home"}"
/>

<com:Email
EmailID="${traveler.email}"
Type="Home"
/>

</com:BookingTraveler>`;


/* ------------------------------------------------
   HOTEL RATE DETAIL XML
------------------------------------------------*/

const hotelRateDetailXML = `
<hotel:HotelRateDetail
RatePlanType="${hotelRateDetail.ratePlanType}"
Base="${hotelRateDetail.base}"
Total="${hotelRateDetail.total}"
>

<hotel:HotelRateByDate
EffectiveDate="${hotelRateDetail.effectiveDate}"
ExpireDate="${hotelRateDetail.expireDate}"
/>

${hotelRateDetail.commissionIndicator ?
`<hotel:Commission Indicator="${hotelRateDetail.commissionIndicator}"/>`
:
`<hotel:Commission Indicator="true"/>`
}

</hotel:HotelRateDetail>`;


/* ------------------------------------------------
   HOTEL PROPERTY
------------------------------------------------*/

const hotelPropertyXML = `
<hotel:HotelProperty
HotelChain="${hotelProperty.chain}"
HotelCode="${hotelProperty.code}"
HotelLocation="${hotelProperty.location}"
${hotelProperty.name ? `Name="${hotelProperty.name}"` : ""}
/>`;


/* ------------------------------------------------
   HOTEL STAY
------------------------------------------------*/

const stayXML = `
<hotel:HotelStay>

<hotel:CheckinDate>${stay.checkin}</hotel:CheckinDate>

<hotel:CheckoutDate>${stay.checkout}</hotel:CheckoutDate>

</hotel:HotelStay>`;


/* ------------------------------------------------
   PAYMENT GUARANTEE
------------------------------------------------*/

const guaranteeXML = `
<com:Guarantee Type="${guarantee.guaranteeType || "Deposit"}">

<com:CreditCard
Type="${guarantee.type}"
Number="${guarantee.number}"
ExpDate="${guarantee.expDate}"
CVV="${guarantee.cvv}"
${guarantee.holderName ? `Name="${guarantee.holderName}"` : ""}
/>

</com:Guarantee>`;


/* ------------------------------------------------
   GUEST INFORMATION
------------------------------------------------*/

const childrenXML = guestInformation.children.length
? `<hotel:NumberOfChildren Count="${guestInformation.children.length}">
${guestInformation.children.map(c=>`<hotel:Age>${c.age}</hotel:Age>`).join("")}
</hotel:NumberOfChildren>`
: "";

const guestXML = `
<hotel:GuestInformation NumberOfRooms="${guestInformation.rooms}">
<hotel:NumberOfAdults>${guestInformation.adults}</hotel:NumberOfAdults>
${childrenXML}
</hotel:GuestInformation>`;


/* ------------------------------------------------
   OPTIONAL XML
------------------------------------------------*/

const loyaltyXML = loyaltyCard
? `<com:LoyaltyCard SupplierCode="${loyaltyCard.supplierCode}" Number="${loyaltyCard.number}"/>`
: "";

const corporateXML = corporateDiscountId
? `<com:CorporateDiscountID>${corporateDiscountId}</com:CorporateDiscountID>`
: "";

const requestXML = specialRequests.length
? specialRequests.map(r=>`<com:SpecialRequest>${r}</com:SpecialRequest>`).join("")
: "";


/* ------------------------------------------------
   FULL SOAP XML
------------------------------------------------*/

const soap = `<?xml version="1.0" encoding="UTF-8"?>

<soapenv:Envelope
xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/"
xmlns:com="http://www.travelport.com/schema/common_v54_0"
xmlns:hotel="http://www.travelport.com/schema/hotel_v54_0"
xmlns:univ="http://www.travelport.com/schema/universal_v54_0">

<soapenv:Body>

<univ:HotelCreateReservationReq
TraceId="${traceId}"
AuthorizedBy="${AUTHORIZED_BY}"
TargetBranch="${TARGET_BRANCH}"
ProviderCode="${PROVIDER}"
RetrieveProviderReservationDetails="true"
UserAcceptance="true"
>

<com:BillingPointOfSaleInfo OriginApplication="UAPI"/>

${bookingTravelerXML}

${hotelRateDetailXML}

${hotelPropertyXML}

${stayXML}

${guaranteeXML}

${guestXML}

${loyaltyXML}

${corporateXML}

${requestXML}

</univ:HotelCreateReservationReq>

</soapenv:Body>

</soapenv:Envelope>`;


/* ------------------------------------------------
   API CALL
------------------------------------------------*/

const response = await axios.post(HOTEL_URL,soap,{
headers:{ "Content-Type":"text/xml" },
auth:{ username:USERNAME,password:PASSWORD }
});


/* ------------------------------------------------
   XML → JSON
------------------------------------------------*/

const parser = new xml2js.Parser({explicitArray:false});
const result = await parser.parseStringPromise(response.data);

return result;

}
catch(err){

console.error("SERVICE ERROR:",err.response?.data || err.message);

throw new Error("Travelport booking failed");

}

};
// <!--Base="${hotelRateDetail.basePerNight}"