
"use strict";
/**
 * airCancelSegmentController.js
 *
 * ╔══════════════════════════════════════════════════════════════════════════════╗
 * ║  CANCEL TYPES                                                                ║
 * ║                                                                              ║
 * ║  TYPE 1 → cancelType: "full_pnr"                                            ║
 * ║           Requires: UniversalLocator                                         ║
 * ║           Cancels:  Entire UR (air + hotel + car + all passengers)           ║
 * ║           Lookup:   uflights.UniversalLocator                                ║
 * ║                                                                              ║
 * ║  TYPE 2 → cancelType: "all_air"                                             ║
 * ║           Requires: AirReservationLocator                                    ║
 * ║           Cancels:  All air segments (hotel/car untouched)                   ║
 * ║           Lookup:   uflights.AirReservationLocator                           ║
 * ║                                                                              ║
 * ║  TYPE 3 → cancelType: "one_segment"                                         ║
 * ║           Requires: AirReservationLocator + segmentKey                       ║
 * ║           Cancels:  One specific flight leg                                  ║
 * ║           Lookup:   uflights.AirReservationLocator                           ║
 * ║                                                                              ║
 * ║  TYPE 4 → cancelType: "cancel_divided_pnr"                                  ║
 * ║           Requires: child_locator + cancelSubType                            ║
 * ║           Lookup:   PnrSplitHistory.child_locator (NOT uflights)             ║
 * ║                                                                              ║
 * ║  TYPE 4 SUB-TYPES:                                                           ║
 * ║    cancelSubType: "full_ur"      → cancel entire child UR                   ║
 * ║    cancelSubType: "one_segment"  → cancel one leg of child PNR              ║
 * ║                                                                              ║
 * ║  PASSENGER COMBINATIONS SUPPORTED IN TYPE 4:                                 ║
 * ║    Single ADT                  → child_locator of that ADT's UR             ║
 * ║    ADT + INF (must be together)→ child_locator of their shared UR           ║
 * ║    Multiple ADTs               → child_locator of their shared UR           ║
 * ║    2ADT + 2INF                 → child_locator of their shared UR           ║
 * ║    CNN alone                   → child_locator of CNN's own UR              ║
 * ║    Each in own UR              → cancel each child_locator separately       ║
 * ║                                                                              ║
 * ║  POSTMAN EXAMPLES:                                                           ║
 * ║                                                                              ║
 * ║  TYPE 1:  { "cancelType": "full_pnr",                                       ║
 * ║             "UniversalLocator": "JRL8B4" }                                  ║
 * ║                                                                              ║
 * ║  TYPE 2:  { "cancelType": "all_air",                                        ║
 * ║             "AirReservationLocator": "H9C4ZS" }                             ║
 * ║                                                                              ║
 * ║  TYPE 3:  { "cancelType": "one_segment",                                    ║
 * ║             "AirReservationLocator": "1O8X0Z",                              ║
 * ║             "segmentKey": "68NHlABAAA==" }                                  ║
 * ║                                                                              ║
 * ║  TYPE 4A: { "cancelType": "cancel_divided_pnr",                             ║
 * ║             "cancelSubType": "full_ur",                                      ║
 * ║             "child_locator": "35CI6R" }                                      ║
 * ║                                                                              ║
 * ║  TYPE 4B: { "cancelType": "cancel_divided_pnr",                             ║
 * ║             "cancelSubType": "one_segment",                                  ║
 * ║             "child_locator": "35CI6R",                                       ║
 * ║             "segmentKey": "pUHyt2Vq==" }                                     ║
 * ╚══════════════════════════════════════════════════════════════════════════════╝
 */

const db = require('../../../busapi/configs/dbConnection');
const {
  cancelEntirePNR,
  cancelAllAirSegments,
  cancelOneAirSegment,
} = require("../services/airCancelSegmentService");

// =============================================================================
// Helper: fetch booking by UniversalLocator — TYPE 1
// =============================================================================
const fetchBookingByUniversalLocator = async (universalLocator) => {
  const [rows] = await db.query(
    `SELECT booking_id, UniversalLocator, AirReservationLocator,
            GdsLocator, SupplierLocator, TraceId, Status
     FROM uflights WHERE UniversalLocator = ? LIMIT 1`,
    [universalLocator]
  );
  if (!rows || rows.length === 0) {
    const e = new Error(`No booking found for UniversalLocator: ${universalLocator}`);
    e.httpStatus = 404; throw e;
  }
  if (rows[0].Status?.toLowerCase() === "cancelled") {
    const e = new Error("This booking is already cancelled");
    e.httpStatus = 400; throw e;
  }
  return rows[0];
};

// =============================================================================
// Helper: fetch booking by AirReservationLocator — TYPE 2 & 3
// =============================================================================
const fetchBookingByAirReservationLocator = async (airReservationLocator) => {
  const [rows] = await db.query(
    `SELECT booking_id, UniversalLocator, AirReservationLocator,
            GdsLocator, SupplierLocator, TraceId, Status
     FROM uflights WHERE AirReservationLocator = ? LIMIT 1`,
    [airReservationLocator]
  );
  if (!rows || rows.length === 0) {
    const e = new Error(`No booking found for AirReservationLocator: ${airReservationLocator}`);
    e.httpStatus = 404; throw e;
  }
  if (rows[0].Status?.toLowerCase() === "cancelled") {
    const e = new Error("This booking is already cancelled");
    e.httpStatus = 400; throw e;
  }
  return rows[0];
};

// =============================================================================
// Helper: fetch all flight segments for a booking
// =============================================================================
const fetchSegments = async (bookingId) => {
  const [rows] = await db.query(
    `SELECT booking_id, segment_id, segment_ref_key,
            Carrier, flight_number, Origin, Destination,
            departure_time, arrival_time, cabin_class, booking_code, segment_status
     FROM FlightSegments WHERE booking_id = ?`,
    [bookingId]
  );
  if (!rows || rows.length === 0) {
    const e = new Error(`No segments found for booking_id: ${bookingId}`);
    e.httpStatus = 404; throw e;
  }
  return rows;
};

// =============================================================================
// Helper: update PassengersDetails for cancelled passengers
//
// Works for ALL passenger counts:
//   1 passenger  → UPDATE WHERE traveler_ref_key = KEY1
//   2 passengers → UPDATE WHERE traveler_ref_key IN (KEY1, KEY2)
//   N passengers → UPDATE WHERE traveler_ref_key IN (KEY1...KEYN)
//
// Also works for all passenger types:
//   ADT, INF, CNN — all updated by traveler_ref_key match
// =============================================================================
const cancelPassengersInDB = async (bookingId, passengerKeys, tag) => {
  if (!bookingId || !passengerKeys || passengerKeys.length === 0) {
    console.warn(`${tag} ⚠️  cancelPassengersInDB: skipped — bookingId=${bookingId} keys=${JSON.stringify(passengerKeys)}`);
    return 0;
  }

  const [result] = await db.query(
    `UPDATE PassengersDetails
     SET status = 'Cancelled'
     WHERE booking_id = ?
       AND traveler_ref_key IN (?)`,
    [bookingId, passengerKeys]
  );

  console.log(`${tag} PassengersDetails updated: ${result.affectedRows} row(s) → Cancelled`);
  console.log(`${tag}   booking_id    : ${bookingId}`);
  console.log(`${tag}   keys updated  : ${passengerKeys.join(", ")}`);

  return result.affectedRows;
};

// =============================================================================
// Helper: check if all segments for a booking are now cancelled
// =============================================================================
const checkAllSegmentsCancelled = async (bookingId) => {
  const [rows] = await db.query(
    `SELECT COUNT(*) AS activeCount
     FROM FlightSegments
     WHERE booking_id = ?
       AND (segment_status IS NULL
            OR segment_status NOT IN ('Cancelled', 'cancelled'))`,
    [bookingId]
  );
  return rows[0].activeCount === 0;
};

// =============================================================================
// Main Controller
// =============================================================================
const cancelAirSegmentController = async (req, res) => {
  const TAG = "[airCancelSegmentController]";

  try {
    const {
      UniversalLocator,
      AirReservationLocator,
      cancelType    = "one_segment",
      cancelSubType,
      segmentKey,
      child_locator,
    } = req.body;

    const validTypes = ["full_pnr", "all_air", "one_segment", "cancel_divided_pnr"];
    if (!validTypes.includes(cancelType)) {
      return res.status(400).json({
        success: false,
        message: `Invalid cancelType. Must be one of: ${validTypes.join(", ")}`,
      });
    }

    console.log(`${TAG} ─────────────────────────────────────────────────────`);
    console.log(`${TAG} cancelType    : ${cancelType}`);
    console.log(`${TAG} cancelSubType : ${cancelSubType || "(not provided)"}`);
    console.log(`${TAG} child_locator : ${child_locator || "(not provided)"}`);
    console.log(`${TAG} segmentKey    : ${segmentKey   || "(not provided)"}`);
    console.log(`${TAG} ─────────────────────────────────────────────────────`);

    // =========================================================================
    // TYPE 1 — Cancel entire Universal Record
    // =========================================================================
    if (cancelType === "full_pnr") {
      if (!UniversalLocator) {
        return res.status(400).json({
          success: false,
          message: "UniversalLocator required for cancelType: full_pnr",
        });
      }

      const booking = await fetchBookingByUniversalLocator(UniversalLocator);
      const { booking_id: bookingId, UniversalLocator: universalLocator, GdsLocator: gdsLocator, TraceId: traceId } = booking;

      const result = await cancelEntirePNR({ universalLocator, gdsLocator, traceId });

      await db.query(`UPDATE uflights SET Status = 'Cancelled' WHERE booking_id = ?`, [bookingId]);
      await db.query(`UPDATE FlightSegments SET segment_status = 'Cancelled' WHERE booking_id = ?`, [bookingId]);
      await db.query(`UPDATE PassengersDetails SET status = 'Cancelled' WHERE booking_id = ?`, [bookingId]);
      console.log(`${TAG} TYPE 1: DB updated ✅`);

      return res.status(200).json({
        success: true,
        message: "Entire PNR cancelled",
        cancelType: "full_pnr",
        data: { bookingId, universalLocator, gdsLocator, urVersion: result.urVersion, travelportResponse: result.cancelRsp },
      });
    }

    // =========================================================================
    // TYPE 2 — Cancel all air segments
    // =========================================================================
    if (cancelType === "all_air") {
      if (!AirReservationLocator) {
        return res.status(400).json({
          success: false,
          message: "AirReservationLocator required for cancelType: all_air",
        });
      }

      const booking = await fetchBookingByAirReservationLocator(AirReservationLocator);
      const { booking_id: bookingId, UniversalLocator: universalLocator, GdsLocator: gdsLocator, TraceId: traceId } = booking;

      const result = await cancelAllAirSegments({ AirReservationLocator, universalLocator, gdsLocator, traceId });

      await db.query(`UPDATE uflights SET Status = 'Cancelled' WHERE booking_id = ?`, [bookingId]);
      await db.query(`UPDATE FlightSegments SET segment_status = 'Cancelled' WHERE booking_id = ?`, [bookingId]);
      await db.query(`UPDATE PassengersDetails SET status = 'Cancelled' WHERE booking_id = ?`, [bookingId]);
      console.log(`${TAG} TYPE 2: DB updated ✅`);

      return res.status(200).json({
        success: true,
        message: "All air segments cancelled",
        cancelType: "all_air",
        data: { bookingId, AirReservationLocator, universalLocator, gdsLocator, urVersion: result.urVersion, cancelledSegments: result.cancelledSegments, travelportResponse: result.airCancelRsp },
      });
    }

    // =========================================================================
    // TYPE 3 — Cancel one specific air segment
    // =========================================================================
    if (cancelType === "one_segment") {
      if (!AirReservationLocator) {
        return res.status(400).json({
          success: false,
          message: "AirReservationLocator required for cancelType: one_segment",
        });
      }

      const booking = await fetchBookingByAirReservationLocator(AirReservationLocator);
      const { booking_id: bookingId, UniversalLocator: universalLocator, GdsLocator: gdsLocator, TraceId: traceId } = booking;

      const segmentRows = await fetchSegments(bookingId);

      let targetSegment;
      if (segmentKey) {
        targetSegment = segmentRows.find((s) => s.segment_ref_key === segmentKey);
        if (!targetSegment) {
          return res.status(404).json({
            success: false,
            message: `segmentKey "${segmentKey}" not found`,
            availableSegments: segmentRows.map((s) => ({
              key: s.segment_ref_key, flight: `${s.Carrier}${s.flight_number}`,
              route: `${s.Origin}->${s.Destination}`, depart: s.departure_time,
            })),
          });
        }
      } else {
        targetSegment = segmentRows[0];
      }

      const result = await cancelOneAirSegment({ AirReservationLocator, universalLocator, gdsLocator, traceId, segment: targetSegment });

      await db.query(
        `UPDATE FlightSegments SET segment_status = 'Cancelled' WHERE booking_id = ? AND segment_ref_key = ?`,
        [bookingId, targetSegment.segment_ref_key]
      );

      const allDone = await checkAllSegmentsCancelled(bookingId);
      if (allDone) {
        await db.query(`UPDATE uflights SET Status = 'Cancelled' WHERE booking_id = ?`, [bookingId]);
        await db.query(`UPDATE PassengersDetails SET status = 'Cancelled' WHERE booking_id = ?`, [bookingId]);
      }
      console.log(`${TAG} TYPE 3: DB updated ✅ allDone=${allDone}`);

      return res.status(200).json({
        success: true,
        message: "Flight segment cancelled",
        cancelType: "one_segment",
        data: {
          bookingId, AirReservationLocator, universalLocator, gdsLocator,
          urVersion: result.urVersion, allSegmentsCancelled: allDone,
          cancelledSegment: {
            dbKey: targetSegment.segment_ref_key, liveKey: result.liveSegment.Key,
            keyChanged: result.liveSegment.Key !== targetSegment.segment_ref_key,
            carrier: targetSegment.Carrier, flightNumber: targetSegment.flight_number,
            origin: targetSegment.Origin, destination: targetSegment.Destination,
            departureTime: targetSegment.departure_time, arrivalTime: targetSegment.arrival_time,
          },
          travelportResponse: result.airCancelRsp,
        },
      });
    }

    // =========================================================================
    // TYPE 4 — Cancel child PNR after ProviderReservationDivideReq
    //
    // HANDLES ALL PASSENGER COMBINATIONS:
    //
    //   SCENARIO A — Each passenger/pair has their OWN child UR:
    //     ADT+INF pair  → child_locator of their UR  (passenger_keys: ["ADT","INF"])
    //     CNN alone     → child_locator of CNN's UR  (passenger_keys: ["CNN"])
    //     Cancel each child_locator separately
    //
    //   SCENARIO B — Multiple passengers share ONE child UR:
    //     2ADT+2INF+CNN → one child_locator          (passenger_keys: ["ADT1","INF1","ADT2","INF2","CNN"])
    //     One cancel call handles all of them
    //
    //   BOTH SCENARIOS use identical cancel logic.
    //   The difference is only in how many keys are in passenger_keys.
    //
    // SUB-TYPES:
    //   full_ur     → UniversalRecordCancelReq — cancels entire child UR
    //                 All passengers in that UR get cancelled.
    //                 Works for: one-way, round-trip (both legs at once)
    //
    //   one_segment → AirCancelReq with segment key
    //                 Cancels one flight leg for all passengers in child UR.
    //                 Works for: round-trip (cancel outbound OR return individually)
    //                 After both legs cancelled → auto-marks all passengers Cancelled
    // =========================================================================
    if (cancelType === "cancel_divided_pnr") {

      if (!child_locator) {
        return res.status(400).json({
          success: false,
          message: "child_locator is required for cancelType: cancel_divided_pnr",
          hint: {
            oneWayOrFullRoundTrip: { cancelType: "cancel_divided_pnr", cancelSubType: "full_ur", child_locator: "35CI6R" },
            oneSegmentRoundTrip:   { cancelType: "cancel_divided_pnr", cancelSubType: "one_segment", child_locator: "35CI6R", segmentKey: "abc==" },
          },
        });
      }

      const validSubTypes = ["full_ur", "one_segment"];
      if (!cancelSubType || !validSubTypes.includes(cancelSubType)) {
        return res.status(400).json({
          success: false,
          message: `cancelSubType required for cancel_divided_pnr. Must be: ${validSubTypes.join(", ")}`,
        });
      }

      console.log(`${TAG} ── TYPE 4 ──────────────────────────────────────────`);
      console.log(`${TAG} child_locator : ${child_locator}`);
      console.log(`${TAG} cancelSubType : ${cancelSubType}`);
      console.log(`${TAG} segmentKey    : ${segmentKey || "(not provided)"}`);

      // ── Fetch from PnrSplitHistory ─────────────────────────────────────────
      const [splitRows] = await db.query(
        `SELECT id, booking_id, parent_locator, child_locator,
                gds_locator, passenger_keys, status
         FROM PnrSplitHistory
         WHERE child_locator = ?
         LIMIT 1`,
        [child_locator]
      );

      if (!splitRows || splitRows.length === 0) {
        return res.status(404).json({
          success: false,
          message: `No divided PNR found in PnrSplitHistory for child_locator: ${child_locator}`,
        });
      }

      const split = splitRows[0];
      console.log(`${TAG} PnrSplitHistory found: id=${split.id} | status=${split.status}`);

      if (split.status?.toLowerCase() === "cancelled") {
        return res.status(400).json({
          success: false,
          message: `Divided PNR (${child_locator}) is already cancelled`,
        });
      }

      const {
        id:             splitHistoryId,
        booking_id:     bookingId,
        child_locator:  childUniversalLocator,
        gds_locator:    childGdsLocator,
        parent_locator: parentLocator,
        passenger_keys: passengerKeysRaw,
      } = split;

      // Parse passenger_keys — works for 1 or N passengers
      let passengerKeys = [];
      try {
        passengerKeys = typeof passengerKeysRaw === "string"
          ? JSON.parse(passengerKeysRaw)
          : passengerKeysRaw || [];
      } catch { passengerKeys = []; }

      console.log(`${TAG} childUR=${childUniversalLocator} | childGDS=${childGdsLocator}`);
      console.log(`${TAG} bookingId=${bookingId} | passengerCount=${passengerKeys.length}`);
      console.log(`${TAG} passengerKeys=${JSON.stringify(passengerKeys)}`);

      // =======================================================================
      // TYPE 4 — SUB-TYPE: full_ur
      //
      // Cancels entire child UR in ONE Travelport call.
      //
      // ONE-WAY cases handled:
      //   Case A1: Single ADT in own child UR
      //   Case A3: CNN in own child UR
      //   Case A-ADT+INF: ADT+INF pair in own child UR
      //   Case B1: Multiple passengers sharing one child UR
      //
      // ROUND TRIP cases handled:
      //   Case A6: ADT+INF round trip, cancel both legs at once
      //   Case B5: All passengers in one UR, cancel both legs at once
      //
      // DB updates:
      //   PnrSplitHistory → Cancelled + cancelled_at
      //   PassengersDetails → Cancelled (ALL keys in passenger_keys)
      //     1 passenger   → 1 row updated
      //     ADT+INF pair  → 2 rows updated (ADT + INF both Cancelled)
      //     2ADT+2INF+CNN → 5 rows updated (all Cancelled)
      // =======================================================================
      if (cancelSubType === "full_ur") {
        console.log(`${TAG} TYPE 4 full_ur: Cancelling entire child UR=${childUniversalLocator}`);
        console.log(`${TAG} Passengers to cancel: ${passengerKeys.length} (${passengerKeys.join(", ")})`);

        const result = await cancelEntirePNR({
          universalLocator: childUniversalLocator,
          gdsLocator:       childGdsLocator,
          traceId:          null,
        });

        // Update PnrSplitHistory
        await db.query(
          `UPDATE PnrSplitHistory SET status = 'Cancelled', cancelled_at = NOW() WHERE id = ?`,
          [splitHistoryId]
        );
        console.log(`${TAG} PnrSplitHistory id=${splitHistoryId} → Cancelled ✅`);

        // Update ALL passengers in this child UR — works for 1, 2, or N keys
        const affectedRows = await cancelPassengersInDB(bookingId, passengerKeys, TAG);

        return res.status(200).json({
          success: true,
          message: `Divided child PNR fully cancelled. ${passengerKeys.length} passenger(s) cancelled.`,
          cancelType:    "cancel_divided_pnr",
          cancelSubType: "full_ur",
          data: {
            splitHistoryId,
            bookingId,
            parentLocator,
            childUniversalLocator,
            childGdsLocator,
            passengersCount:        passengerKeys.length,
            cancelledPassengerKeys: passengerKeys,
            passengersDBUpdated:    affectedRows,
            urVersion:              result.urVersion,
            travelportResponse:     result.cancelRsp,
          },
        });
      }

      // =======================================================================
      // TYPE 4 — SUB-TYPE: one_segment
      //
      // Cancels ONE flight leg of the child UR.
      // ALL passengers in the child UR have that leg cancelled.
      //
      // ROUND TRIP cases handled:
      //   Case A4: ADT+INF — cancel outbound only
      //   Case A5: ADT+INF — cancel return only
      //   Case B2: Multiple pax — cancel outbound only
      //   Case B3: Multiple pax — cancel return only
      //   Case B4: After both legs cancelled one by one → auto full cancel
      //
      // DB updates after segment cancel:
      //   FlightSegments: target segment → Cancelled
      //
      //   If ALL segments now Cancelled (both legs done):
      //     PnrSplitHistory    → Cancelled + cancelled_at
      //     PassengersDetails  → Cancelled (all keys in passenger_keys)
      //
      //   If other segment still Active (one leg remaining):
      //     PnrSplitHistory    → stays Active
      //     PassengersDetails  → stays Active
      // =======================================================================
      if (cancelSubType === "one_segment") {
        if (!segmentKey) {
          return res.status(400).json({
            success: false,
            message: "segmentKey required for cancelSubType: one_segment",
            hint: 'Add "segmentKey": "<value from FlightSegments.segment_ref_key>"',
          });
        }

        console.log(`${TAG} TYPE 4 one_segment: segmentKey=${segmentKey}`);

        // Fetch target segment from FlightSegments
        const [segRows] = await db.query(
          `SELECT booking_id, segment_id, segment_ref_key,
                  Carrier, flight_number, Origin, Destination,
                  departure_time, arrival_time, cabin_class, booking_code, segment_status
           FROM FlightSegments
           WHERE booking_id = ? AND segment_ref_key = ?
           LIMIT 1`,
          [bookingId, segmentKey]
        );

        if (!segRows || segRows.length === 0) {
          const [allSegs] = await db.query(
            `SELECT segment_ref_key, Carrier, flight_number,
                    Origin, Destination, departure_time, segment_status
             FROM FlightSegments WHERE booking_id = ?`,
            [bookingId]
          );
          return res.status(404).json({
            success: false,
            message: `segmentKey "${segmentKey}" not found for booking_id=${bookingId}`,
            availableSegments: (allSegs || []).map((s) => ({
              key: s.segment_ref_key, flight: `${s.Carrier}${s.flight_number}`,
              route: `${s.Origin}->${s.Destination}`,
              depart: s.departure_time, status: s.segment_status,
            })),
          });
        }

        const targetSegment = segRows[0];
        console.log(`${TAG} Target: ${targetSegment.Carrier}${targetSegment.flight_number} ${targetSegment.Origin}->${targetSegment.Destination}`);

        // Cancel the segment — service extracts live AirReservationLocator from UR
        const result = await cancelOneAirSegment({
          AirReservationLocator: childGdsLocator,      // service overrides with live value
          universalLocator:      childUniversalLocator,
          gdsLocator:            childGdsLocator,
          traceId:               null,
          segment:               targetSegment,
        });

        // Mark this segment as Cancelled
        await db.query(
          `UPDATE FlightSegments SET segment_status = 'Cancelled'
           WHERE booking_id = ? AND segment_ref_key = ?`,
          [bookingId, segmentKey]
        );
        console.log(`${TAG} FlightSegments: ${segmentKey} → Cancelled ✅`);

        // Check if ALL segments for this booking are now cancelled
        const allSegmentsDone = await checkAllSegmentsCancelled(bookingId);
        console.log(`${TAG} allSegmentsDone=${allSegmentsDone}`);

        let affectedRows = 0;
        if (allSegmentsDone) {
          // All legs cancelled → full passenger cancel
          await db.query(
            `UPDATE PnrSplitHistory SET status = 'Cancelled', cancelled_at = NOW() WHERE id = ?`,
            [splitHistoryId]
          );
          console.log(`${TAG} PnrSplitHistory id=${splitHistoryId} → Cancelled ✅`);

          // Cancel ALL passengers in this child UR (1, 2, or N)
          affectedRows = await cancelPassengersInDB(bookingId, passengerKeys, TAG);
        } else {
          console.log(`${TAG} Other segments still active → PnrSplitHistory + PassengersDetails stay Active`);
        }

        return res.status(200).json({
          success: true,
          message: allSegmentsDone
            ? `Segment cancelled. All legs done — ${passengerKeys.length} passenger(s) fully cancelled.`
            : `Segment cancelled. Passenger(s) still have other active leg(s).`,
          cancelType:    "cancel_divided_pnr",
          cancelSubType: "one_segment",
          data: {
            splitHistoryId,
            bookingId,
            parentLocator,
            childUniversalLocator,
            childGdsLocator,
            passengersCount:        passengerKeys.length,
            allSegmentsCancelled:   allSegmentsDone,
            cancelledPassengerKeys: allSegmentsDone ? passengerKeys : [],
            passengersDBUpdated:    affectedRows,
            cancelledSegment: {
              dbKey:         targetSegment.segment_ref_key,
              liveKey:       result.liveSegment.Key,
              keyChanged:    result.liveSegment.Key !== targetSegment.segment_ref_key,
              carrier:       targetSegment.Carrier,
              flightNumber:  targetSegment.flight_number,
              origin:        targetSegment.Origin,
              destination:   targetSegment.Destination,
              departureTime: targetSegment.departure_time,
              arrivalTime:   targetSegment.arrival_time,
            },
            urVersion:          result.urVersion,
            travelportResponse: result.airCancelRsp,
          },
        });
      }
    }

  } catch (error) {
    console.error(`${TAG} Error: ${error.message}`);
    console.error(error.stack);
    return res.status(error.httpStatus || 500).json({
      success: false,
      message: error.httpStatus ? error.message : "Internal server error during cancellation",
      error: error.message,
    });
  }
};

module.exports = cancelAirSegmentController;
