"use strict";
const travelportClient = require("../utils/travelportClient");
const xml2js = require("xml2js");
const fs = require("fs");
const path = require("path");
const db = require('../../../busapi/configs/dbConnection');
 
 
/**
* Helper to parse the XML result and insert into SQL tables 
* Includes: Unique Keys (GUIDs), Tax Breakdowns, and precise Locator mapping.
*/
async function saveToInternalDatabase(result, traceId, payload) {
  try {
    
    // ✅ SAFE EXTRACTION (NO ?. USED)
    const uid = payload && payload.uid ? payload.uid : null;
    const contactInfo = payload && payload.contactInfo ? payload.contactInfo : {};

    const pemail = contactInfo.email ? contactInfo.email : null;
    const pmobile = contactInfo.phone && contactInfo.phone.number
      ? contactInfo.phone.number
      : null;

    const envelope = result.data || result;

    const body = envelope && envelope['SOAP:Envelope']
      ? envelope['SOAP:Envelope']['SOAP:Body']
      : null;

    const response = body && body['universal:AirCreateReservationRsp']
      ? body['universal:AirCreateReservationRsp']
      : null;

    const ur = response && response['universal:UniversalRecord']
      ? response['universal:UniversalRecord']
      : null;

    // --- FIX: Normalize AirReservation ---
    const airResRaw = ur && ur['air:AirReservation'] ? ur['air:AirReservation'] : null;
    const airRes = Array.isArray(airResRaw) ? airResRaw[0] : airResRaw;

    const uLocator = ur && ur.$ ? ur.$.LocatorCode : null;

    // --- FIX: Safe locator extraction ---
    const airReservationLocator =
      (airRes && airRes.$ && airRes.$.LocatorCode) ||
      (ur && ur.$ && ur.$.LocatorCode) ||
      null;

    // --- NORMALIZATION ---
    const pricingInfosRaw = airRes && airRes['air:AirPricingInfo']
      ? airRes['air:AirPricingInfo']
      : null;

    const pricingInfos = pricingInfosRaw
      ? (Array.isArray(pricingInfosRaw) ? pricingInfosRaw : [pricingInfosRaw])
      : [];

    const segmentsRaw = airRes && airRes['air:AirSegment']
      ? airRes['air:AirSegment']
      : null;

    const segments = segmentsRaw
      ? (Array.isArray(segmentsRaw) ? segmentsRaw : [segmentsRaw])
      : [];

    // --- 1. INSERT INTO uflights ---
    const resSql = `INSERT INTO uflights 
      (uid, pemail, pmobile, UniversalLocator, AirReservationLocator, GdsLocator, SupplierLocator, Status, TotalPrice, BasePrice, Taxes, CreateDate, TraceId) 
      VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`;

    const mainPricing = pricingInfos && pricingInfos[0] && pricingInfos[0].$
      ? pricingInfos[0].$
      : {};

    const supplier = airRes &&
      airRes['common_v54_0:SupplierLocator'] &&
      airRes['common_v54_0:SupplierLocator'].$
      ? airRes['common_v54_0:SupplierLocator'].$.SupplierLocatorCode
      : null;

    const providerInfo = ur && ur['universal:ProviderReservationInfo']
      ? ur['universal:ProviderReservationInfo']
      : null;

    const [resResult] = await db.execute(resSql, [
      uid,
      pemail,
      pmobile,
      uLocator,
      airReservationLocator,
      providerInfo && providerInfo.$ ? providerInfo.$.LocatorCode : null,
      supplier,
      ur && ur.$ ? ur.$.Status : null,
      mainPricing.TotalPrice || null,
      mainPricing.BasePrice || null,
      mainPricing.Taxes || null,
      providerInfo && providerInfo.$ ? providerInfo.$.CreateDate : null,
      traceId
    ]);

    const bookingId = resResult.insertId;

    // --- 2. INSERT INTO Passengers ---
    // const travelersRaw = ur && ur['common_v54_0:BookingTraveler']
    //   ? ur['common_v54_0:BookingTraveler']
    //   : null;

    // const travelers = travelersRaw
    //   ? (Array.isArray(travelersRaw) ? travelersRaw : [travelersRaw])
    //   : [];

    // for (let pax of travelers) {
    //   const name = pax && pax['common_v54_0:BookingTravelerName'] && pax['common_v54_0:BookingTravelerName'].$
    //     ? pax['common_v54_0:BookingTravelerName'].$
    //     : {};

    //   const paxSql = `INSERT INTO PassengersDetails 
    //     (booking_id, traveler_ref_key, first_name, last_name, prefix, traveler_type, age, dob, gender) 
    //     VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)`;

    //   await db.execute(paxSql, [
    //     bookingId,
    //     pax && pax.$ ? pax.$.Key : null,
    //     name.First || null,
    //     name.Last || null,
    //     name.Prefix || null,
    //     pax && pax.$ ? pax.$.TravelerType : null,
    //     pax && pax.$ ? pax.$.Age : null,
    //     pax && pax.$ ? pax.$.DOB : null,
    //     pax && pax.$ ? pax.$.Gender : null
    //   ]);
    // }


// Enhanced passenger extraction - FIX THIS SECTION
const travelersRaw = ur && ur['common_v54_0:BookingTraveler']
  ? ur['common_v54_0:BookingTraveler']
  : null;

console.log(`[${traceId}] Raw travelersRaw type: ${typeof travelersRaw}`);
console.log(`[${traceId}] Is Array: ${Array.isArray(travelersRaw)}`);
console.log(`[${traceId}] travelersRaw value:`, JSON.stringify(travelersRaw, null, 2));

let travelers = [];

if (travelersRaw) {
  if (Array.isArray(travelersRaw)) {
    travelers = travelersRaw;
    console.log(`[${traceId}] Case 1: travelers is array, length = ${travelers.length}`);
  } 
  else if (typeof travelersRaw === 'object') {
    // Check if it's a single object with $ property (single passenger)
    if (travelersRaw.$ && travelersRaw['common_v54_0:BookingTravelerName']) {
      travelers = [travelersRaw];
      console.log(`[${traceId}] Case 2: Single passenger object`);
    }
    // Check if it's an object with numeric keys (array-like from xml2js)
    else {
      const keys = Object.keys(travelersRaw);
      console.log(`[${traceId}] Case 3: Object with keys: ${keys.join(', ')}`);
      // Extract values that look like passenger objects
      travelers = keys
        .filter(key => !isNaN(parseInt(key)) || key === '0' || key === '1' || key === '2')
        .map(key => travelersRaw[key])
        .filter(item => item && item.$ && item.$.TravelerType);
      console.log(`[${traceId}] Extracted ${travelers.length} passengers from object keys`);
    }
  }
}

console.log(`[${traceId}] Final travelers count: ${travelers.length}`);

// Log each passenger found
for (let i = 0; i < travelers.length; i++) {
  const pax = travelers[i];
  const paxAttrs = pax && pax.$ ? pax.$ : {};
  const name = pax && pax['common_v54_0:BookingTravelerName'] && pax['common_v54_0:BookingTravelerName'].$
    ? pax['common_v54_0:BookingTravelerName'].$
    : {};
  console.log(`[${traceId}] Passenger ${i}: Type=${paxAttrs.TravelerType}, Name=${name.First} ${name.Last}`);
}

// Now insert passengers
for (let pax of travelers) {
  const name = pax && pax['common_v54_0:BookingTravelerName'] && pax['common_v54_0:BookingTravelerName'].$
    ? pax['common_v54_0:BookingTravelerName'].$
    : {};

  const travelerType = pax && pax.$ ? pax.$.TravelerType : null;
  
  // Build the values array
  const paxValues = [
    bookingId,
    pax && pax.$ ? pax.$.Key : null,
    name.First || null,
    name.Last || null,
    name.Prefix || null,
    travelerType,
    pax && pax.$ ? pax.$.Age : null,
    pax && pax.$ ? pax.$.DOB : null,
    pax && pax.$ ? pax.$.Gender : null
  ];
  
  // Log the actual values being inserted
  console.log(`[${traceId}] 📝 Inserting ${travelerType}:`, {
    booking_id: paxValues[0],
    traveler_ref_key: paxValues[1],
    first_name: paxValues[2],
    last_name: paxValues[3],
    prefix: paxValues[4],
    traveler_type: paxValues[5],
    age: paxValues[6],
    dob: paxValues[7],
    gender: paxValues[8]
  });

  const paxSql = `INSERT INTO PassengersDetails 
    (booking_id, traveler_ref_key, first_name, last_name, prefix, traveler_type, age, dob, gender) 
    VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)`;

  try {
    const [result] = await db.execute(paxSql, paxValues);
    console.log(`[${traceId}] ✅ ${travelerType} inserted, affectedRows: ${result.affectedRows}`);
  } catch (sqlError) {
    console.error(`[${traceId}] ❌ Failed to insert ${travelerType}:`, sqlError.message);
    console.error(`[${traceId}]    Values:`, JSON.stringify(paxValues));
  }
}

    // --- 3. INSERT INTO FlightSegments ---
    for (let seg of segments) {
      const segKey = seg && seg.$ ? seg.$.Key : null;
      let bCode = null;

      for (let info of pricingInfos) {
        const bInfosRaw = info && info['air:BookingInfo']
          ? info['air:BookingInfo']
          : null;

        const bInfos = bInfosRaw
          ? (Array.isArray(bInfosRaw) ? bInfosRaw : [bInfosRaw])
          : [];

        const match = bInfos.find(bi => bi && bi.$ && bi.$.SegmentRef === segKey);
        if (match) {
          bCode = match.$.BookingCode;
          break;
        }
      }

      const segSql = `INSERT INTO FlightSegments 
        (booking_id, segment_ref_key, carrier, flight_number, origin, destination, departure_time, arrival_time, cabin_class, booking_code) 
        VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`;

      await db.execute(segSql, [
        bookingId,
        segKey,
        seg && seg.$ ? seg.$.Carrier : null,
        seg && seg.$ ? seg.$.FlightNumber : null,
        seg && seg.$ ? seg.$.Origin : null,
        seg && seg.$ ? seg.$.Destination : null,
        seg && seg.$ ? seg.$.DepartureTime : null,
        seg && seg.$ ? seg.$.ArrivalTime : null,
        seg && seg.$ ? seg.$.CabinClass : null,
        bCode
      ]);
    }

    // --- 4. INSERT INTO Fare & Tax ---
    for (let info of pricingInfos) {
      const pKey = info && info.$ ? info.$.Key : null;

      const fareInfosRaw = info && info['air:FareInfo']
        ? info['air:FareInfo']
        : null;

      const fareInfos = fareInfosRaw
        ? (Array.isArray(fareInfosRaw) ? fareInfosRaw : [fareInfosRaw])
        : [];

      for (let fInfo of fareInfos) {
        const fare = fInfo && fInfo.$ ? fInfo.$ : null;
        if (!fare) continue;

        const fareSql = `INSERT INTO FareBreakdown 
          (booking_id, pricing_info_key, passenger_type, amount, fare_basis) 
          VALUES (?, ?, ?, ?, ?)`;

        await db.execute(fareSql, [
          bookingId,
          pKey,
          fare.PassengerTypeCode || null,
          fare.Amount || null,
          fare.FareBasis || null
        ]);
      }

      const taxesRaw = info && info['air:TaxInfo']
        ? info['air:TaxInfo']
        : null;

      const taxes = taxesRaw
        ? (Array.isArray(taxesRaw) ? taxesRaw : [taxesRaw])
        : [];

      for (let tax of taxes) {
        const taxData = tax && tax.$ ? tax.$ : null;
        if (!taxData) continue;

        const numericAmount = parseFloat(
          (taxData.Amount || '').replace(/[^\d.]/g, '')
        );

        const taxSql = `INSERT INTO TaxBreakdown 
          (booking_id, pricing_info_key, category, amount) 
          VALUES (?, ?, ?, ?)`;

        await db.execute(taxSql, [
          bookingId,
          pKey,
          taxData.Category || null,
          numericAmount || 0
        ]);
      }
    }
    
    console.log(`[DB-SUCCESS] Stored reservation ${uLocator}`);
    return true;

  } catch (dbErr) {
    console.error(`[DB-SAVE-ERROR] TraceId: ${traceId}`, dbErr);
    return false;
  }
}
const {
  TARGET_BRANCH,
  TRAVELPORT_AIR_SERVICE,
  AUTHORIZED_BY = "BOBROS",
  AGENCY_PHONE,
  AGENCY_LOCATION,
  AGENCY_COUNTRY_CODE,
  AGENCY_AREA_CODE,
  AGENCY_TEXT
} = process.env;
const AGENCY_CONFIG = {
  Location: AGENCY_LOCATION || "HYD",
  CountryCode: AGENCY_COUNTRY_CODE || "0091",
  AreaCode: AGENCY_AREA_CODE || "040",
  Number: AGENCY_PHONE || "8096503272",
  Text: AGENCY_TEXT || "BOBROS CONSULTANCY SERVICES PVT LTD"
};
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 formatDateForRemark = (dateStr) => {
  if (!dateStr) return "";
  const d = new Date(dateStr);
  const months = ["JAN","FEB","MAR","APR","MAY","JUN","JUL","AUG","SEP","OCT","NOV","DEC"];
  return `${String(d.getUTCDate()).padStart(2, "0")}${months[d.getUTCMonth()]}${String(d.getUTCFullYear()).slice(-2)}`;
};
const validateAndSanitizeName = (name) => {
  if (!name) return "";
  return name.replace(/[^a-zA-Z\s\-']/g, "").trim();
};
const getPassengerPrefix = (pax, isInfant, carrier) => {
  if (isInfant) return null;
  if (pax.prefix) return pax.prefix;
  if (carrier === "6E" || carrier === "AK") {
    return pax.gender === "F" ? "MS" : "MR";
  }
  if (pax.code === "CNN" && pax.gender === "M") return "MSTR";
  return pax.gender === "F" ? "MS" : "MR";
};
async function createPNR(payload) {
  const { 
    traceId, 
    passengers, 
    segments, 
    airPricingSolution,
    contactInfo,
    formOfPayment,
    autoTicket = false 
  } = payload;
  
  const schemaVersion = "v54_0";
  const primaryCarrier = segments && segments[0] ? segments[0].carrier : "AI";
  const providerCode = primaryCarrier === "6E" ? "ACH" : "1G";
  const timestamp = Date.now();

  // Validate required data
  if (!passengers || !passengers.length) {
    throw new Error("No passengers provided");
  }
  if (!segments || !segments.length) {
    throw new Error("No flight segments provided");
  }
  if (!airPricingSolution) {
    throw new Error("No air pricing solution provided");
  }

  // Build XML manually based on working sample
  let xml = `<?xml version="1.0" encoding="UTF-8"?>
<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:univ="http://www.travelport.com/schema/universal_${schemaVersion}" xmlns:air="http://www.travelport.com/schema/air_${schemaVersion}" xmlns:com="http://www.travelport.com/schema/common_${schemaVersion}">
<soapenv:Body>
<univ:AirCreateReservationReq TraceId="${traceId}" AuthorizedBy="${AUTHORIZED_BY}" TargetBranch="${TARGET_BRANCH}" ProviderCode="${providerCode}" RetainReservation="Both" ConnectivityCheckoverride="Yes" RestrictWaitlist="false">
<com:BillingPointOfSaleInfo OriginApplication="UAPI"/>`;

  // Add BookingTravelers
  const sortedPassengers = [...passengers].sort((a, b) => {
    const order = { ADT: 1, INF: 2, CNN: 3 };
    return (order[a.code] || 4) - (order[b.code] || 4);
  });

  sortedPassengers.forEach((pax, idx) => {
    const travelerKey = String(idx + 1);
    const isInfant = pax.code === "INF";
    const prefix = getPassengerPrefix(pax, isInfant, primaryCarrier);
    
    const firstName = validateAndSanitizeName(pax.firstName);
    const lastName = validateAndSanitizeName(pax.lastName);
    
    xml += `
<com:BookingTraveler Key="${travelerKey}" TravelerType="${pax.code}"${pax.age ? ` Age="${pax.age}"` : ''}${pax.dob ? ` DOB="${pax.dob}"` : ''}${pax.gender ? ` Gender="${pax.gender}"` : ''}${pax.nationality ? ` Nationality="${pax.nationality}"` : ''}>
<com:BookingTravelerName First="${firstName}" Last="${lastName}"${prefix ? ` Prefix="${prefix}"` : ''}/>`;
    
    const docSsrFreeText = `P/${pax.nationality || 'IN'}/PASS/${formatDateForRemark(pax.dob)}/${pax.gender || 'M'}/01JAN35/${lastName}/${firstName}`;
    xml += `
<com:SSR Type="DOCS" Status="HK" Carrier="${primaryCarrier}" FreeText="${docSsrFreeText}"/>`;
    
    if (idx === 0 && contactInfo && contactInfo.phone && contactInfo.phone.number) {
      xml += `
<com:SSR Type="CTCM" Status="HK" Carrier="${primaryCarrier}" FreeText="/${contactInfo.phone.countryCode || '91'}${contactInfo.phone.number}"/>`;
    }
    
    if (idx === 0 && contactInfo && contactInfo.email) {
        const formattedEmail = contactInfo.email.replace('@', '//');
      xml += `<com:SSR Type="CTCE" Status="HK" Carrier="${primaryCarrier}" FreeText="/${formattedEmail}"/>`;
    }
    
    if (pax.code === "INF") {
      xml += `
<com:NameRemark>
<com:RemarkData>${formatDateForRemark(pax.dob)}</com:RemarkData>
</com:NameRemark>`;
    } else if (pax.code === "CNN") {
      const age = String(pax.age).padStart(2, "0");
      xml += `
<com:NameRemark>
<com:RemarkData>P-C${age} DOB${formatDateForRemark(pax.dob)}</com:RemarkData>
</com:NameRemark>`;
    }
    
    xml += `
</com:BookingTraveler>`;
  });

  // Add AgencyContactInfo
  xml += `
<com:AgencyContactInfo>
<com:PhoneNumber Type="Agency" Location="${AGENCY_CONFIG.Location}" CountryCode="${AGENCY_CONFIG.CountryCode}" AreaCode="${AGENCY_CONFIG.AreaCode}" Number="${AGENCY_CONFIG.Number}" Text="${AGENCY_CONFIG.Text}"/>
</com:AgencyContactInfo>`;

  // Add FormOfPayment
  if (formOfPayment && formOfPayment.type === "CreditCard") {
    xml += `
<com:FormOfPayment Type="CreditCard" Key="FOP1">
<com:CreditCard CVV="${formOfPayment.cvv}" ExpDate="${formOfPayment.expDate}" Name="${formOfPayment.cardHolderName}" Number="${formOfPayment.cardNumber}" Type="${formOfPayment.cardType}"/>
</com:FormOfPayment>`;
  }
  else if (providerCode === "ACH" || (formOfPayment && formOfPayment.type === "AgencyPayment")) {
    xml += `
<com:FormOfPayment Type="AgencyPayment" Key="FOP1">
<com:AgencyPayment AgencyBillingIdentifier="${formOfPayment && formOfPayment.agencyBillingId ? formOfPayment.agencyBillingId : process.env.AGENCY_BILLING_ID}" AgencyBillingPassword="${formOfPayment && formOfPayment.agencyBillingPassword ? formOfPayment.agencyBillingPassword : process.env.AGENCY_BILLING_PASSWORD}"/>
</com:FormOfPayment>`;
  } else {
    xml += `
<com:FormOfPayment Type="Cash" Key="FOP1"/>`;
  }

  // Add AirPricingSolution - FIX 1: Add Fees="INR0" if not present
  xml += `
<air:AirPricingSolution Key="${airPricingSolution.key}" TotalPrice="${airPricingSolution.totalPrice}" BasePrice="${airPricingSolution.basePrice}" ApproximateTotalPrice="${airPricingSolution.totalPrice}" ApproximateBasePrice="${airPricingSolution.basePrice}"${airPricingSolution.fees ? ` Fees="${airPricingSolution.fees}"` : ' Fees="INR0"'}${airPricingSolution.taxes ? ` Taxes="${airPricingSolution.taxes}"` : ''}>`;

  // Add AirSegments - FIX 2: Add CodeshareInfo
  segments.forEach((segment, idx) => {
    xml += `
<air:AirSegment Key="${segment.key}" Group="${segment.group || '0'}" Carrier="${segment.carrier}" FlightNumber="${segment.flightNumber}" Origin="${segment.origin}" Destination="${segment.destination}" DepartureTime="${segment.departureTime}" ArrivalTime="${segment.arrivalTime}" ProviderCode="${providerCode}" ClassOfService="${segment.classOfService}"${segment.flightTime ? ` FlightTime="${segment.flightTime}"` : ''}${segment.travelTime ? ` TravelTime="${segment.travelTime}"` : ''}${segment.distance ? ` Distance="${segment.distance}"` : ''}${segment.equipment ? ` Equipment="${segment.equipment}"` : ''}${segment.changeOfPlane ? ` ChangeOfPlane="${segment.changeOfPlane}"` : ''}${segment.optionalServicesIndicator ? ` OptionalServicesIndicator="${segment.optionalServicesIndicator}"` : ''}${segment.availabilitySource ? ` AvailabilitySource="${segment.availabilitySource}"` : ''}${segment.participantLevel ? ` ParticipantLevel="${segment.participantLevel}"` : ''}${segment.linkAvailability ? ` LinkAvailability="${segment.linkAvailability}"` : ''}${segment.availabilityDisplayType ? ` AvailabilityDisplayType="${segment.availabilityDisplayType}"` : ''}>
<air:CodeshareInfo OperatingCarrier="${segment.carrier}"/>
</air:AirSegment>`;
  });

  // Add AirPricingInfo - FIX 3: Add PricingMethod="Auto"
  if (airPricingSolution.airPricingInfo && airPricingSolution.airPricingInfo.length) {
    airPricingSolution.airPricingInfo.forEach((info, idx) => {
      xml += `
<air:AirPricingInfo Key="${info.key}" TotalPrice="${info.totalPrice}" BasePrice="${info.basePrice}" ApproximateTotalPrice="${info.totalPrice}" ApproximateBasePrice="${info.basePrice}" ProviderCode="${providerCode}" PricingMethod="Auto"${info.fareType ? ` FareType="${info.fareType}"` : ''}${info.fareIndicator ? ` FareIndicator="${info.fareIndicator}"` : ''}${info.latestTicketingTime ? ` LatestTicketingTime="${info.latestTicketingTime}"` : ''}${info.refundable ? ` Refundable="${info.refundable}"` : ''}${info.eticketability ? ` ETicketability="${info.eticketability}"` : ''}${info.platingCarrier ? ` PlatingCarrier="${info.platingCarrier}"` : ''}>`;

      // Add FareInfo - FIX 4: Add Amount attribute (empty string if not provided)
      if (info.fareInfos && info.fareInfos.length) {
        info.fareInfos.forEach(fareInfo => {
          xml += `
<air:FareInfo Key="${fareInfo.key}" FareBasis="${fareInfo.fareBasis}" PassengerTypeCode="${fareInfo.passengerTypeCode}" Origin="${fareInfo.origin}" Destination="${fareInfo.destination}" EffectiveDate="${fareInfo.effectiveDate}" DepartureDate="${fareInfo.departureDate}" Amount="${fareInfo.amount || ''}" PrivateFare="${fareInfo.privateFare || 'false'}" NegotiatedFare="${fareInfo.negotiatedFare || 'false'}"${fareInfo.promotionalFare ? ` PromotionalFare="${fareInfo.promotionalFare}"` : ''}>`;
          if (fareInfo.fareRuleKey) {
            xml += `
<air:FareRuleKey FareInfoRef="${fareInfo.key}" ProviderCode="${providerCode}">${fareInfo.fareRuleKey}</air:FareRuleKey>`;
          }
          xml += `
</air:FareInfo>`;
        });
      }

      // Add BookingInfo
      if (info.bookingInfos && info.bookingInfos.length) {
        info.bookingInfos.forEach(bookingInfo => {
          xml += `
<air:BookingInfo BookingCode="${bookingInfo.bookingCode}" FareInfoRef="${bookingInfo.fareInfoRef}" SegmentRef="${bookingInfo.segmentRef}" CabinClass="${bookingInfo.cabinClass || 'Economy'}"${bookingInfo.hostTokenRef ? ` HostTokenRef="${bookingInfo.hostTokenRef}"` : ''}/>`;
        });
      }

      // Add PassengerType
      if (info.passengerTypes && info.passengerTypes.length) {
        info.passengerTypes.forEach(pt => {
          xml += `
<air:PassengerType Code="${pt.code}" BookingTravelerRef="${pt.bookingTravelerRef}"${pt.age ? ` Age="${pt.age}"` : ''}${pt.code === "INF" ? ` PricePTCOnly="true"` : ''}/>`;
        });
      }

      xml += `
</air:AirPricingInfo>`;
    });
  }

  // Add HostTokens if present
  if (airPricingSolution.hostTokens && airPricingSolution.hostTokens.length) {
    airPricingSolution.hostTokens.forEach(token => {
      xml += `
<com:HostToken Key="${token.key}">${token.value}</com:HostToken>`;
    });
  }

  xml += `
</air:AirPricingSolution>`;

  // Add ActionStatus - FIX 5: Add TicketDate="T*"
  xml += `
<com:ActionStatus Type="ACTIVE" ProviderCode="${providerCode}" TicketDate="T*"/>`;

  // Add Payment
  xml += `
<com:Payment Key="PAY1" Type="Itinerary" FormOfPaymentRef="FOP1" Amount="${airPricingSolution.totalPrice}"/>`;

  xml += `
</univ:AirCreateReservationReq>
</soapenv:Body>
</soapenv:Envelope>`;

  // Save debug XML
  saveDebugXml(`AirCreateReq-${traceId}-${timestamp}.xml`, xml);
  console.log(`[${traceId}] Request XML saved to debug folder`);

  try {
    const response = await travelportClient.post(TRAVELPORT_AIR_SERVICE, xml);
    saveDebugXml(`AirCreateRsp-${traceId}-${timestamp}.xml`, response.data);
    
    const parser = new xml2js.Parser({ explicitArray: false, mergeAttrs: false });
    const result = await parser.parseStringPromise(response.data);
    
    if (result) {
      await saveToInternalDatabase(result, traceId, payload);
    }
    
    return {
      success: true,
      traceId: traceId,
      data: result
    };
    
  } catch (error) {
    console.error(`[${traceId}] PNR Create Error:`, error.message);
    return {
      success: false,
      traceId: traceId,
      error: error.message
    };
  }
}

module.exports = { createPNR };

module.exports = { createPNR };