// "use strict";
// const travelportClient = require("../utils/travelportClient");
// const xml2js = require("xml2js");
// const fs = require("fs");
// const path = require("path");

// const saveDebugXml = (fileName, xmlData) => {
//   try {
//     const debugDir = path.resolve(__dirname, "..", "debug-xml");
//     if (!fs.existsSync(debugDir)) fs.mkdirSync(debugDir, { recursive: true });
//     fs.writeFileSync(path.join(debugDir, fileName), xmlData);
//   } catch (err) {
//     console.error(`[DEBUG-LOG-ERR] ${err.message}`);
//   }
// };

// const buildFOPXml = (fop) => {
//   if (!fop || fop.type === "Cash") {
//     return `<com:FormOfPayment xmlns:com="http://www.travelport.com/schema/common_v54_0" Type="Cash"/>`;
//   }
//   if (fop.type === "CreditCard") {
//     return `<com:FormOfPayment xmlns:com="http://www.travelport.com/schema/common_v54_0" Type="CreditCard">
//               <com:CreditCard Type="${fop.cardType}" Number="${fop.number}" CVV="${fop.cvv}" ExpDate="${fop.expDate}" Name="${fop.name || 'TEST TRAVELPORT'}"/>
//             </com:FormOfPayment>`;
//   }
//   return `<com:FormOfPayment xmlns:com="http://www.travelport.com/schema/common_v54_0" Type="Cash"/>`;
// };

// const issueTicket = async (pnr, pricingKeys, options = {}) => {
//   const traceId = options.traceId || `BOBROS-${Date.now()}`;
//   const fopXml = buildFOPXml(options.fop);

 
//   if (!Array.isArray(pricingKeys)) {
//     pricingKeys = [pricingKeys];
//   }

// //   const pricingRefsXml = pricingKeys
// //     .map((key) => `<AirPricingInfoRef Key="${key}"/>`)
// //     .join("");

// //   const ticketingXML = `<?xml version="1.0" encoding="UTF-8"?>
// // <soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">
// //   <soap:Body>
// //     <AirTicketingReq xmlns="http://www.travelport.com/schema/air_v54_0" TargetBranch="${process.env.TARGET_BRANCH.trim()}" TraceId="${traceId}" AuthorizedBy="Travelport" ReturnUniversalRecord="true">
// //         <BillingPointOfSaleInfo xmlns="http://www.travelport.com/schema/common_v54_0" OriginApplication="UAPI"/>
// //         <AirReservationLocatorCode>${pnr}</AirReservationLocatorCode>

// //         ${pricingRefsXml}

// //         <AirTicketingModifiers>
// //           ${fopXml}
// //         </AirTicketingModifiers>
// //     </AirTicketingReq>
// //   </soap:Body>
// // </soap:Envelope>`.trim();

// const ticketingModifiersXml = pricingKeys
//   .map(
//     (key) => `
//       <AirTicketingModifiers>
//         <AirPricingInfoRef Key="${key}"/>
//         ${fopXml}
//       </AirTicketingModifiers>
//     `
//   )
//   .join("");

// const ticketingXML = `<?xml version="1.0" encoding="UTF-8"?>
// <soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">
//   <soap:Body>
//     <AirTicketingReq xmlns="http://www.travelport.com/schema/air_v54_0"
//       TargetBranch="${process.env.TARGET_BRANCH.trim()}"
//       TraceId="${traceId}"
//       AuthorizedBy="BOBROS"
//       ReturnUniversalRecord="true">

//         <BillingPointOfSaleInfo xmlns="http://www.travelport.com/schema/common_v54_0" OriginApplication="UAPI"/>
//         <AirReservationLocatorCode>${pnr}</AirReservationLocatorCode>

//         ${ticketingModifiersXml}

//     </AirTicketingReq>
//   </soap:Body>
// </soap:Envelope>`.trim();

//   // ✅ LOG REQUEST
//   saveDebugXml(`AirTicketingReq-${traceId}.xml`, ticketingXML);
//   console.log(`[${traceId}] Ticketing Request XML saved`);

//   try {
//     const response = await travelportClient.post(
//       process.env.TRAVELPORT_AIR_SERVICE,
//       ticketingXML,
//       {
//         headers: {
//           SOAPAction:
//             "http://www.travelport.com/service/air_v54_0/AirTicketingPortType/AirTicketingReq",
//         },
//       }
//     );

//     // ✅ LOG RESPONSE
//     saveDebugXml(`AirTicketingRsp-${traceId}.xml`, response.data);
//     console.log(`[${traceId}] Ticketing Response XML saved`);

//     const parser = new xml2js.Parser({
//       explicitArray: false,
//       ignoreAttrs: false,
//     });
//     const parsedData = await parser.parseStringPromise(response.data);

//     return { traceId, data: parsedData };
//   } catch (error) {
//     const errorData = error.response?.data || error.message;

//     // ✅ LOG ERROR
//     if (typeof errorData === "string") {
//       saveDebugXml(`AirTicketingErr-${traceId}.xml`, errorData);
//       console.log(`[${traceId}] Ticketing Error XML saved`);
//     }

//     if (typeof errorData === "string" && errorData.includes("Envelope")) {
//       const parser = new xml2js.Parser({
//         explicitArray: false,
//         ignoreAttrs: false,
//       });
//       const parsedError = await parser.parseStringPromise(errorData);
//       return { traceId, data: parsedError };
//     }

//     throw new Error(errorData);
//   }
// };

// module.exports = { issueTicket };







"use strict";
const travelportClient = require("../utils/travelportClient");
const xml2js = require("xml2js");
const fs = require("fs");
const path = require("path");

const saveDebugXml = (fileName, xmlData) => {
  try {
    const debugDir = path.resolve(__dirname, "..", "debug-xml");
    if (!fs.existsSync(debugDir)) fs.mkdirSync(debugDir, { recursive: true });
    fs.writeFileSync(path.join(debugDir, fileName), xmlData);
  } catch (err) {
    console.error(`[DEBUG-LOG-ERR] ${err.message}`);
  }
};

const issueTicket = async (pnr, options = {}) => {
  const traceId = options.traceId || `BOBROS-${Date.now()}`;

  const ticketingXML = `<?xml version="1.0" encoding="UTF-8"?>
<soap:Envelope xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">
  <soap:Body>
    <AirTicketingReq TargetBranch="${process.env.TARGET_BRANCH.trim()}" TraceId="${traceId}" AuthorizedBy="BOBROS" ReturnInfoOnFail="true" BulkTicket="false" xmlns="http://www.travelport.com/schema/air_v54_0">
      <BillingPointOfSaleInfo OriginApplication="UAPI" xmlns="http://www.travelport.com/schema/common_v54_0"/>
      <AirReservationLocatorCode>${pnr}</AirReservationLocatorCode>
    </AirTicketingReq>
  </soap:Body>
</soap:Envelope>`.trim();

  // LOG REQUEST
  saveDebugXml(`AirTicketingReq-${traceId}.xml`, ticketingXML);
  console.log(`[${traceId}] Ticketing Request XML saved`);

  try {
    const response = await travelportClient.post(
      process.env.TRAVELPORT_AIR_SERVICE,
      ticketingXML,
      {
        headers: {
          SOAPAction:
            "http://www.travelport.com/service/air_v54_0/AirTicketingPortType/AirTicketingReq",
        },
      }
    );

    // LOG RESPONSE
    saveDebugXml(`AirTicketingRsp-${traceId}.xml`, response.data);
    console.log(`[${traceId}] Ticketing Response XML saved`);

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

    return { traceId, data: parsedData };
  } catch (error) {
    const errorData = error.response?.data || error.message;

    // LOG ERROR
    if (typeof errorData === "string") {
      saveDebugXml(`AirTicketingErr-${traceId}.xml`, errorData);
      console.log(`[${traceId}] Ticketing Error XML saved`);
    }

    if (typeof errorData === "string" && errorData.includes("Envelope")) {
      const parser = new xml2js.Parser({
        explicitArray: false,
        ignoreAttrs: false,
      });
      const parsedError = await parser.parseStringPromise(errorData);
      return { traceId, data: parsedError };
    }

    throw new Error(errorData);
  }
};

module.exports = { issueTicket };