// // models/travelportModel.js
// const axios = require('axios');

// exports.lowFareSearch = async (params) => {
//   try {
//     // Example Travelport API call (replace with your endpoint + auth)
//     const response = await axios.post("https://api.bobros.org/flights/lowfare", {
//       source: params.source,
//       destination: params.destination,
//       date: params.date
//     }, {
//       headers: {
//         'Authorization': `Bearer ${process.env.TRAVELPORT_TOKEN}`,
//         'Content-Type': 'application/json'
//       }
//     });

//     return response.data;
//   } catch (error) {
//     console.error('Error calling Travelport API:', error.message);
//     throw error;
//   }
// };

// const axios = require('axios');

// exports.lowFareSearch = async (params) => {
//   const requestBody = {
//     legs: [
//       {
//         origin: params.source,
//         destination: params.destination,
//         departureDate: params.date
//       }
//     ],
//     cabinClass: params.cabinClass || "Economy",
//     passengers: [
//       { type: "ADT", count: 1 }
//     ]
//   };

//   const response = await axios.post(
//     "https://api.bobros.org/flights/lowfare",
//     requestBody,
//     {
//       headers: {
//         "Authorization": `Bearer ${process.env.TRAVELPORT_TOKEN}`,
//         "Content-Type": "application/json"
//       }
//     }
//   );

//   return response.data;
// };

// exports.lowFareSearch = async (params) => {
//   const requestBody = {
//     legs: [
//       {
//         origin: params.source,
//         destination: params.destination,
//         departureDate: params.date
//       }
//     ],
//     cabinClass: params.cabinClass || "Economy",
//     passengers: [
//       { passengerType: "ADT", quantity: 1 },   // ✅ adult passenger
//       { passengerType: "INF", quantity: 1, age: 1 } // ✅ infant passenger
//     ]
//   };
//   console.log("Request body:", JSON.stringify(requestBody, null, 2));


//   const response = await axios.post(
//     "https://api.bobros.org/flights/lowfare",
//     requestBody,
//     {
//       headers: {
//         "Authorization": `Bearer ${process.env.TRAVELPORT_TOKEN}`,
//         "Content-Type": "application/json"
//       }
//     }
//   );

//   return response.data;
// };

// "use strict";

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

// // ─────────────────────────────────────────────────────────────
// // ENV VARIABLES (set in .env)
// // ─────────────────────────────────────────────────────────────
// const URL = process.env.TRAVELPORT_AIR_SERVICE;
// const USERNAME = process.env.TRAVELPORT_USERNAME;
// const PASSWORD = process.env.TRAVELPORT_PASSWORD;
// const TARGET_BRANCH = process.env.TARGET_BRANCH;
// //const PCC            = process.env.TRAVELPORT_PCC || "P7001234";

// // ─────────────────────────────────────────────────────────────
// // XML Builder
// // ─────────────────────────────────────────────────────────────

// function buildLowFareSearchXML(source, destination, doj, passengers) {
//   const { adults = 1, children = 0, infants = 0, cabinClass = "Economy" } = passengers;

//   let passengerXML = "";

//   // Adults
//   for (let i = 0; i < adults; i++) {
//     passengerXML += `<com:SearchPassenger Code="ADT"/>`;
//   }

//   // Children
//   for (let i = 0; i < children; i++) {
//     passengerXML += `<com:SearchPassenger Code="CNN"/>`;
//   }

//   // Infants
//   for (let i = 0; i < infants; i++) {
//     passengerXML += `<com:SearchPassenger Code="INF"/>`;
//   }

//   return `
// <soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/"
//                   xmlns:air="http://www.travelport.com/schema/air_v54_0"
//                   xmlns:com="http://www.travelport.com/schema/common_v54_0">
//   <soapenv:Header/>
//   <soapenv:Body>
//     <air:LowFareSearchReq TraceId="test"
//                          TargetBranch="${TARGET_BRANCH}"
//                          AuthorizedBy="${USERNAME.replace(/[^a-zA-Z0-9]/g, '')}"
//                          SolutionResult="true">
      
//       <com:BillingPointOfSaleInfo OriginApplication="UAPI"/>

//       <air:SearchAirLeg>
//         <air:SearchOrigin>
//           <com:Airport Code="${source}"/>
//         </air:SearchOrigin>
//         <air:SearchDestination>
//           <com:Airport Code="${destination}"/>
//         </air:SearchDestination>
//         <air:SearchDepTime PreferredTime="${doj}"/>
//       </air:SearchAirLeg>

//       <air:AirSearchModifiers>
//         <air:PreferredCabins>
//           <com:CabinClass Type="${cabinClass.toUpperCase()}"/>
//         </air:PreferredCabins>
//       </air:AirSearchModifiers>

//       ${passengerXML}

//     </air:LowFareSearchReq>
//   </soapenv:Body>
// </soapenv:Envelope>
// `;
// }

// // ─────────────────────────────────────────────────────────────
// // MAIN SERVICE FUNCTION
// // ─────────────────────────────────────────────────────────────

// exports.fetchLowFareSearch = async (
//   source,
//   destination,
//   doj,
//   passengers = {}
// ) => {
//   try {
//     const xmlRequest = buildLowFareSearchXML(
//       source,
//       destination,
//       doj,
//       passengers
//     );

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

//     // Convert XML → JSON
//     const parsed = await xml2js.parseStringPromise(response.data, {
//       explicitArray: false,
//       ignoreAttrs: false,
//     });
//     console.log("parsed:", parsed);
//     return {
//       success: true,
//       data: parsed,
//     };

//   } catch (error) {
//     console.error("LowFareSearch Error:", error?.response?.data || error.message);

//     return {
//       success: false,
//       error: error?.response?.data || error.message,
//     };
//   }
// };


"use strict";

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

// ─────────────────────────────────────────────────────────────
// ENV VARIABLES (set in .env)
// ─────────────────────────────────────────────────────────────
const URL = process.env.TRAVELPORT_AIR_SERVICE;
const USERNAME = process.env.TRAVELPORT_USERNAME;
const PASSWORD = process.env.TRAVELPORT_PASSWORD;
const TARGET_BRANCH = process.env.TARGET_BRANCH;
//const PCC            = process.env.TRAVELPORT_PCC || "P7001234";

// ─────────────────────────────────────────────────────────────
// XML Builder
// ─────────────────────────────────────────────────────────────

function buildLowFareSearchXML(source, destination, doj, passengers) {
  const { adults = 1, children = 0, infants = 0, cabinClass = "Economy" } = passengers;

  let passengerXML = "";

  // Adults
  for (let i = 0; i < adults; i++) {
    passengerXML += `<com:SearchPassenger Code="ADT"/>`;
  }

  // Children
  for (let i = 0; i < children; i++) {
    passengerXML += `<com:SearchPassenger Code="CNN"/>`;
  }

  // Infants
  for (let i = 0; i < infants; i++) {
    passengerXML += `<com:SearchPassenger Code="INF"/>`;
  }
  
  const generateTraceId = () => {
  return `BOBROS-${Date.now()}`;
};

  return `
<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/"
                  xmlns:air="http://www.travelport.com/schema/air_v54_0"
                  xmlns:com="http://www.travelport.com/schema/common_v54_0">
  <soapenv:Header/>
  <soapenv:Body>
    <air:LowFareSearchReq TraceId="${generateTraceId()}"
                         TargetBranch="${TARGET_BRANCH}"
                         AuthorizedBy="${USERNAME.replace(/[^a-zA-Z0-9]/g, '')}"
                         SolutionResult="true">
      
      <com:BillingPointOfSaleInfo OriginApplication="UAPI"/>

      <air:SearchAirLeg>
        <air:SearchOrigin>
          <com:Airport Code="${source}"/>
        </air:SearchOrigin>
        <air:SearchDestination>
          <com:Airport Code="${destination}"/>
        </air:SearchDestination>
        <air:SearchDepTime PreferredTime="${doj}"/>
      </air:SearchAirLeg>

      <air:AirSearchModifiers>
        <air:PreferredCabins>
          <com:CabinClass Type="${cabinClass.toUpperCase()}"/>
        </air:PreferredCabins>
      </air:AirSearchModifiers>

      ${passengerXML}

    </air:LowFareSearchReq>
  </soapenv:Body>
</soapenv:Envelope>
`;
}

// ─────────────────────────────────────────────────────────────
// MAIN SERVICE FUNCTION
// ─────────────────────────────────────────────────────────────

exports.fetchLowFareSearch = async (
  source,
  destination,
  doj,
  passengers = {}
) => {
  try {
    const xmlRequest = buildLowFareSearchXML(
      source,
      destination,
      doj,
      passengers
    );

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

    // Convert XML → JSON
    const parsed = await xml2js.parseStringPromise(response.data, {
      explicitArray: false,
      ignoreAttrs: false,
    });
    console.log("parsed:", parsed);
    return {
      success: true,
      data: parsed,
    };

  } catch (error) {
    console.error("LowFareSearch Error:", error?.response?.data || error.message);

    return {
      success: false,
      error: error?.response?.data || error.message,
    };
  }
};