const normalizeArray = (v) =>
  Array.isArray(v) ? v : v ? [v] : [];

/**
 * Safely extract LowFareSearchRsp (handles namespaces)
 */
function getLowFareRsp(result) {
  if (!result) return null;

  if (
    result["SOAP:Envelope"] &&
    result["SOAP:Envelope"]["SOAP:Body"]
  ) {
    return result["SOAP:Envelope"]["SOAP:Body"]["air:LowFareSearchRsp"];
  }

  if (result.Envelope && result.Envelope.Body) {
    return (
      result.Envelope.Body["air:LowFareSearchRsp"] ||
      result.Envelope.Body.LowFareSearchRsp
    );
  }

  return null;
}

module.exports = function buildFlightResults(result) {
  const rsp = getLowFareRsp(result);

  if (!rsp) {
    console.error("❌ LowFareSearchRsp not found");
    return [];
  }

  /* ---------------- RAW LISTS ---------------- */

  const airSegments = normalizeArray(
    rsp["air:AirSegmentList"]?.["air:AirSegment"]
  );

  const flightDetailsList = normalizeArray(
    rsp["air:FlightDetailsList"]?.["air:FlightDetails"]
  );

  const airPricePoints = normalizeArray(
    rsp["air:AirPricePointList"]?.["air:AirPricePoint"]
  );

  const fareInfoList = normalizeArray(
    rsp["air:FareInfoList"]?.["air:FareInfo"]
  );

  const brandList = normalizeArray(
    rsp["air:BrandList"]?.["air:Brand"]
  );

  /* ---------------- INDEX MAPS ---------------- */

  const segmentMap = {};
  airSegments.forEach((s) => {
    segmentMap[s.$.Key] = s;
  });

  const flightDetailsMap = {};
  flightDetailsList.forEach((fd) => {
    flightDetailsMap[fd.$.Key] = fd;
  });

  const fareInfoMap = {};
  fareInfoList.forEach((fi) => {
    fareInfoMap[fi.$.Key] = fi;
  });

  const brandMap = {};
  brandList.forEach((b) => {
    brandMap[b.$.Key] = b;
  });

  /* ---------------- MERGING ---------------- */

  const flights = [];

  airPricePoints.forEach((pp) => {
    const pricingInfo = pp["air:AirPricingInfo"];
    if (!pricingInfo) return;

    const flightOptions = normalizeArray(
      pricingInfo["air:FlightOptionsList"]?.["air:FlightOption"]
    );

    flightOptions.forEach((fo) => {
      const options = normalizeArray(fo["air:Option"]);

      options.forEach((opt) => {
        const bookingInfos = normalizeArray(opt["air:BookingInfo"]);

        bookingInfos.forEach((bi) => {
          const segmentRef = bi?.$?.SegmentRef;
          if (!segmentRef) return;

          const segment = segmentMap[segmentRef];
          if (!segment) return;

          /* -------- FLIGHT DETAILS -------- */

          const flightDetailsKey =
            segment["air:FlightDetailsRef"]?.$?.Key || null;

          const flightDetails =
            flightDetailsMap[flightDetailsKey] || null;

          /* -------- FARE INFO → BRAND -------- */

          let fareInfo = null;
          let brand = null;

          if (bi.$?.FareInfoRef && fareInfoMap[bi.$.FareInfoRef]) {
            fareInfo = fareInfoMap[bi.$.FareInfoRef];

            const brandKey =
              fareInfo["air:Brand"]?.$?.Key || null;

            if (brandKey && brandMap[brandKey]) {
              brand = brandMap[brandKey];
            }
          }

          /* ---------------- FINAL OBJECT ---------------- */

          flights.push({
            /* 🔑 REQUIRED KEYS FOR NEXT APIs */
            keys: {
              airPricePointKey: pp.$.Key,
              airPricingInfoKey: pricingInfo.$.Key,
              airSegmentKey: segment.$.Key,
              flightDetailsKey: flightDetailsKey,
              fareInfoRef: bi.$.FareInfoRef || null,
              hostTokenRef: bi.$.HostTokenRef || null,
              taxInfoRef: bi.$.TaxInfoRef || null,
            },

            /* ✈️ AIR SEGMENT (FULL, AS-IS) */
            segment: {
              ...segment.$,
              APISRequirementsRef:
                segment.$.APISRequirementsRef || null,

              codeshare: segment["air:CodeshareInfo"]
                ? {
                    text: segment["air:CodeshareInfo"]._ || null,
                    ...segment["air:CodeshareInfo"].$,
                  }
                : null,

              provider:
                segment["air:AirAvailInfo"]?.$?.ProviderCode ||
                null,
            },

            /* 🕒 FLIGHT DETAILS (FULL) */
            flightDetails: flightDetails
              ? { ...flightDetails.$ }
              : null,

            /* 💰 PRICING */
            pricing: {
              airPricePoint: {
                total: pp.$.TotalPrice,
                base: pp.$.BasePrice,
                taxes: pp.$.Taxes,
                approximateTotal: pp.$.ApproximateTotalPrice,
                approximateBase: pp.$.ApproximateBasePrice,
                approximateTaxes: pp.$.ApproximateTaxes,
              },
            },

            /* 🎟 AVAILABILITY */
            availability: {
              bookingCode: bi.$.BookingCode,
              bookingCount: Number(bi.$.BookingCount),
              cabinClass: bi.$.CabinClass, // Economy (correct)
            },

            /* 💼 FARE INFO (THIS WAS MISSING BEFORE) */
            fare: fareInfo
              ? {
                  key: fareInfo.$.Key,
                  fareBasis: fareInfo.$.FareBasis,
                  fareFamily: fareInfo.$.FareFamily,
                  passengerType: fareInfo.$.PassengerTypeCode,
                  amount: fareInfo.$.Amount,
                  promotional:
                    fareInfo.$.PromotionalFare === "true",
                  supplier: fareInfo.$.SupplierCode,
                }
              : null,

            /* 🏷 BRAND (FULL WITH TEXT + IMAGES) */
            brand: brand
              ? {
                  ...brand.$,
                  titles: normalizeArray(brand["air:Title"]),
                  texts: normalizeArray(brand["air:Text"]),
                  images: normalizeArray(
                    brand["air:ImageLocation"]
                  ),
                }
              : null,
          });
        });
      });
    });
  });

  return flights;
};
