// const airRetrieveDocumentService = require("../services/airRetrieveDocumentService");


// // ─────────────────────────────────────────────────────────────────────────────
// // ENV CONSTANTS — loaded ONCE at startup, never per request
// //
// // WHY load at module level (not inside the handler):
// //   Reading process.env inside a function on every request is wasteful.
// //   These values never change while the server is running, so reading them
// //   once at startup and storing in constants is the correct pattern.
// //
// // PROVIDER_CODE:
// //   "1G" = Galileo  |  "1V" = Worldspan  |  "1P" = Apollo
// //   This is a server-level setting — it never changes per request.
// //   Frontend should never decide which GDS provider to use.
// // ─────────────────────────────────────────────────────────────────────────────
// const ENV_TARGET_BRANCH  = process.env.TARGET_BRANCH   || '';
// const ENV_AUTHORIZED_BY  = process.env.AUTHORIZED_BY   || 'TEST';
// const ENV_PROVIDER_CODE  = process.env.PROVIDER_CODE   || '';   // e.g. "1G"
// const ENV_TRACE_PREFIX   = process.env.TRACE_ID_PREFIX || 'FLOW';

// // Startup guard — log resolved values so misconfiguration is caught immediately
// console.log('\n[AirRetrieveDocumentController] ENV loaded:');
// console.log(`  TARGET_BRANCH  : ${ENV_TARGET_BRANCH  || '✗ NOT SET — add TARGET_BRANCH to .env'}`);
// console.log(`  AUTHORIZED_BY  : ${ENV_AUTHORIZED_BY}`);
// console.log(`  PROVIDER_CODE  : ${ENV_PROVIDER_CODE  || '✗ NOT SET — add PROVIDER_CODE to .env'}`);
// console.log(`  TRACE_PREFIX   : ${ENV_TRACE_PREFIX}\n`);

// // [Common #5 & #7] Auto-generate unique alphanumeric TraceId
// // Used when frontend starts a NEW booking flow (no traceId sent yet).
// // For continuing an existing flow, frontend sends the same traceId back.
// const generateTraceId = () => `${ENV_TRACE_PREFIX}-${Date.now()}`;

// /**
//  * POST /api/air/retrieve-document
//  *
//  * REQUIRED (send these):
//  *   providerCode         string   e.g. "1G"
//  *   providerLocatorCode  string   e.g. "GBKLC3"
//  *   ticketNumber         string   13-digit e.g. "0985804166538"
//  *
//  * AUTO from .env (do NOT send these — server reads from .env):
//  *   targetBranch   ← TARGET_BRANCH
//  *   authorizedBy   ← AUTHORIZED_BY
//  *
//  * OPTIONAL (send to override defaults):
//  *   traceId                   string    Send if continuing existing booking flow
//  *   returnRestrictions        boolean   default: true
//  *   returnPricing             boolean   default: true
//  *   retrieveMCO               boolean   default: true
//  *   retrieveAgencyInfo        boolean   default: false
//  *   retrieveCannedRemark      boolean   default: false
//  *   originApplication         string    default: "Travel"
//  *   airReservationLocatorCode string    Option 1 (all PNR tickets) vs Option 2 (by ticket#)
//  */
// const retrieveDocument = async (req, res) => {
//   const requestStartTime = Date.now();
//   const requestId = `ARD-${Date.now()}-${Math.random().toString(36).substring(2, 9).toUpperCase()}`;

//   console.log('\n╔══════════════════════════════════════════════════════════╗');
//   console.log(`║  ${new Date().toISOString()}`);
//   console.log('║  AirRetrieveDocument — INCOMING REQUEST');
//   console.log(`║  Internal RequestId : ${requestId}`);
//   console.log('╚══════════════════════════════════════════════════════════╝');
//   console.log(`[${requestId}] Method  : ${req.method}`);
//   console.log(`[${requestId}] URL     : ${req.originalUrl}`);
//   console.log(`[${requestId}] IP      : ${req.ip || req.connection?.remoteAddress}`);
//   console.log(`[${requestId}] Body    : ${JSON.stringify(req.body, null, 2)}`);

//   // ── STEP 1: EXTRACT ──────────────────────────────────────────────────────
//   console.log(`\n[${requestId}] ── STEP 1: Extracting fields...`);

//   // Required from request body — locator and ticket only
//   // providerCode is intentionally NOT here — it comes from .env below
//   const { providerLocatorCode, ticketNumber } = req.body;

//   // traceId: reuse from frontend if continuing a flow, else generate new one
//   const traceId    = req.body.traceId || generateTraceId();
//   const isNewFlow  = !req.body.traceId;

//   // Always from .env — frontend never sends these, server owns them
//   const targetBranch = ENV_TARGET_BRANCH;
//   const authorizedBy = ENV_AUTHORIZED_BY;
//   const providerCode = ENV_PROVIDER_CODE;

//   // Optional — frontend can override; defaults used if absent
//   const {
//     returnRestrictions       = true,
//     returnPricing            = true,
//     retrieveMCO              = true,
//     retrieveAgencyInfo       = false,
//     retrieveCannedRemark     = false,
//     originApplication        = 'Travel',
//     airReservationLocatorCode,
//   } = req.body;

//   console.log(`[${requestId}] ── Auto-resolved from .env:`);
//   console.log(`[${requestId}]   traceId      : ${traceId}  ${isNewFlow ? '← AUTO-GENERATED (new flow)' : '← FROM REQUEST (continuing flow)'}  [Common #5 & #7]`);
//   console.log(`[${requestId}]   targetBranch : ${targetBranch}  ← .env TARGET_BRANCH`);
//   console.log(`[${requestId}]   authorizedBy : ${authorizedBy}  ← .env AUTHORIZED_BY`);
//   console.log(`[${requestId}]   providerCode : ${providerCode}  ← .env PROVIDER_CODE`);
//   console.log(`[${requestId}] ── Required from request body:`);
//   console.log(`[${requestId}]   providerLocatorCode  : ${providerLocatorCode}`);
//   console.log(`[${requestId}]   ticketNumber         : ${ticketNumber}`);
//   console.log(`[${requestId}] ── Optional (defaults applied where not sent):`);
//   console.log(`[${requestId}]   returnRestrictions        : ${returnRestrictions}`);
//   console.log(`[${requestId}]   returnPricing             : ${returnPricing}`);
//   console.log(`[${requestId}]   retrieveMCO               : ${retrieveMCO}`);
//   console.log(`[${requestId}]   retrieveAgencyInfo        : ${retrieveAgencyInfo}`);
//   console.log(`[${requestId}]   retrieveCannedRemark      : ${retrieveCannedRemark}`);
//   console.log(`[${requestId}]   originApplication         : ${originApplication}`);
//   console.log(`[${requestId}]   airReservationLocatorCode : ${airReservationLocatorCode ?? '(not sent → Option 2: by TicketNumber only)'}`);

//   // ── STEP 2: VALIDATE ─────────────────────────────────────────────────────
//   console.log(`\n[${requestId}] ── STEP 2: Validating...`);

//   // Server config guards — .env must have these set
//   const missingEnvVars = [];
//   if (!targetBranch) missingEnvVars.push('TARGET_BRANCH');
//   if (!providerCode) missingEnvVars.push('PROVIDER_CODE');

//   if (missingEnvVars.length > 0) {
//     console.error(`[${requestId}] ✗ SERVER CONFIG ERROR — missing .env vars: [${missingEnvVars.join(', ')}]`);
//     return res.status(500).json({
//       success: false, requestId,
//       error:   'Server Configuration Error',
//       message: `Server is missing required .env variable(s): ${missingEnvVars.join(', ')}. Contact the server administrator.`,
//       missingEnvVars,
//     });
//   }
//   console.log(`[${requestId}] ✓ Server config valid — TARGET_BRANCH: "${targetBranch}", PROVIDER_CODE: "${providerCode}"`);

//   // User-required fields
//   const missingFields = [];
//   if (!providerLocatorCode) missingFields.push('providerLocatorCode');
//   if (!ticketNumber)        missingFields.push('ticketNumber');

//   if (missingFields.length > 0) {
//     console.warn(`[${requestId}] ✗ VALIDATION FAILED — Missing: [${missingFields.join(', ')}]`);
//     return res.status(400).json({
//       success: false, requestId,
//       error:   'Validation Error',
//       message: `Missing required field(s): ${missingFields.join(', ')}`,
//       missingFields,
//     });
//   }

//   // [Common #5 & #7] traceId must be alphanumeric + hyphens only
//   if (!/^[a-zA-Z0-9\-]+$/.test(traceId)) {
//     console.warn(`[${requestId}] ✗ traceId "${traceId}" has invalid characters.  [Common #5 & #7]`);
//     return res.status(400).json({
//       success: false, requestId,
//       error:   'Validation Error',
//       message: 'traceId must contain only alphanumeric characters and hyphens.',
//       checklistRef: 'Common #5 & #7',
//     });
//   }
//   console.log(`[${requestId}] ✓ [Common #5 & #7] traceId valid: "${traceId}"`);

//   // ticketNumber — exactly 13 numeric digits
//   if (!/^\d{13}$/.test(ticketNumber)) {
//     console.warn(`[${requestId}] ✗ ticketNumber "${ticketNumber}" is not 13 digits.`);
//     return res.status(400).json({
//       success: false, requestId,
//       error:   'Validation Error',
//       message: 'ticketNumber must be exactly 13 numeric digits.',
//     });
//   }
//   console.log(`[${requestId}] ✓ ticketNumber valid: "${ticketNumber}"`);
//   console.log(`[${requestId}] ✓ All validations PASSED.`);

//   // ── STEP 3: BUILD SERVICE PAYLOAD ────────────────────────────────────────
//   console.log(`\n[${requestId}] ── STEP 3: Building service payload...`);

//   const servicePayload = {
//     traceId,           // auto-generated or reused from frontend
//     targetBranch,      // always from .env
//     authorizedBy,      // always from .env
//     providerCode,
//     providerLocatorCode,
//     ticketNumber,
//     returnRestrictions,
//     returnPricing,
//     retrieveMCO,
//     retrieveAgencyInfo,
//     retrieveCannedRemark,
//     originApplication,
//     ...(airReservationLocatorCode ? { airReservationLocatorCode } : {}),
//   };

//   console.log(`[${requestId}] Service payload: ${JSON.stringify(servicePayload, null, 2)}`);
//   console.log(`[${requestId}] airReservationLocatorCode → ${servicePayload.airReservationLocatorCode ? `INCLUDED → Option 1` : 'OMITTED → Option 2'}`);

//   // ── STEP 4: CALL SERVICE ─────────────────────────────────────────────────
//   console.log(`\n[${requestId}] ── STEP 4: Calling AirRetrieveDocumentService...`);
//   const t0 = Date.now();

//   let result;
//   try {
//     result = await airRetrieveDocumentService.retrieveDocument(servicePayload, requestId);
//     console.log(`[${requestId}] ✓ Service returned in ${Date.now() - t0}ms`);
//   } catch (error) {
//     const elapsed = Date.now() - t0;
//     console.error(`\n[${requestId}] ✗ SERVICE ERROR after ${elapsed}ms`);
//     console.error(`[${requestId}]   Name    : ${error.name}`);
//     console.error(`[${requestId}]   Message : ${error.message}`);
//     console.error(`[${requestId}]   Stack   :\n${error.stack}`);

//     if (error.isSoapFault) {
//       console.error(`[${requestId}]   Code   : ${error.faultCode}`);
//       console.error(`[${requestId}]   String : ${error.faultString}`);
//       console.error(`[${requestId}]   Detail : ${JSON.stringify(error.faultDetail, null, 2)}`);
//       return res.status(502).json({
//         success: false, requestId,
//         error:       'Travelport SOAP Fault',
//         faultCode:   error.faultCode,
//         faultString: error.faultString,
//         faultDetail: error.faultDetail,
//       });
//     }
//     if (error.code === 'ECONNREFUSED' || error.code === 'ENOTFOUND') {
//       return res.status(503).json({
//         success: false, requestId,
//         error:   'Service Unavailable',
//         message: 'Unable to connect to Travelport.',
//       });
//     }
//     if (error.code === 'ETIMEDOUT' || error.message?.toLowerCase().includes('timeout')) {
//       return res.status(504).json({
//         success: false, requestId,
//         error:   'Gateway Timeout',
//         message: 'Travelport did not respond in time.',
//       });
//     }
//     return res.status(500).json({
//       success: false, requestId,
//       error:   'Internal Server Error',
//       message: error.message || 'An unexpected error occurred.',
//     });
//   }

//   // ── STEP 5: SEND RESPONSE ─────────────────────────────────────────────────
//   const totalDuration = Date.now() - requestStartTime;
//   console.log(`\n[${requestId}] ── STEP 5: Preparing response...`);

//   // _raw is logged for Travelport certification but EXCLUDED from API response
//   // because it is identical to eTickets — sending both doubles the payload size
//   // and confuses frontend consumers with redundant data.
//   const { _raw, ...cleanResult } = result;
//   console.log(`[${requestId}] _raw (${JSON.stringify(_raw).length} chars) logged above — excluded from response`);
//   console.log(`[${requestId}] Clean response: ${JSON.stringify(cleanResult, null, 2)}`);
//   console.log(`[${requestId}] Total duration : ${totalDuration}ms`);
//   console.log('╔══════════════════════════════════════════════════════════╗');
//   console.log(`║  [${requestId}] COMPLETE — ${totalDuration}ms`);
//   console.log('╚══════════════════════════════════════════════════════════╝\n');

//   return res.status(200).json({
//     success:    true,
//     requestId,
//     traceId,        // echo back — frontend must reuse for next step in flow
//     durationMs: totalDuration,
//     data:       cleanResult,
//   });
// };
// module.exports = retrieveDocument;




// /


const airRetrieveDocumentService = require("../services/airRetrieveDocumentService");
const db = require('../../../busapi/configs/dbConnection');

// ─────────────────────────────────────────────────────────────────────────────
// ENV CONSTANTS
// ─────────────────────────────────────────────────────────────────────────────
const ENV_TARGET_BRANCH  = process.env.TARGET_BRANCH   || '';
const ENV_AUTHORIZED_BY  = process.env.AUTHORIZED_BY   || 'TEST';
const ENV_PROVIDER_CODE  = process.env.PROVIDER_CODE   || '';
const ENV_TRACE_PREFIX   = process.env.TRACE_ID_PREFIX || 'FLOW';

console.log('\n[AirRetrieveDocumentController] ENV loaded:');
console.log(`  TARGET_BRANCH  : ${ENV_TARGET_BRANCH  || '✗ NOT SET'}`);
console.log(`  AUTHORIZED_BY  : ${ENV_AUTHORIZED_BY}`);
console.log(`  PROVIDER_CODE  : ${ENV_PROVIDER_CODE  || '✗ NOT SET'}`);
console.log(`  TRACE_PREFIX   : ${ENV_TRACE_PREFIX}\n`);

const generateTraceId = () => `${ENV_TRACE_PREFIX}-${Date.now()}`;

/**
 * POST /api/air/retrieve-document
 *
 * REQUIRED (send these from frontend):
 *   pnr       string   e.g. "GBKLC3"
 *   lastName  string   e.g. "SMITH"
 */
const retrieveDocument = async (req, res) => {
  const requestStartTime = Date.now();
  const requestId = `ARD-${Date.now()}-${Math.random().toString(36).substring(2, 9).toUpperCase()}`;

  console.log('\n╔══════════════════════════════════════════════════════════╗');
  console.log(`║  ${new Date().toISOString()}`);
  console.log('║  AirRetrieveDocument — INCOMING REQUEST');
  console.log(`║  Internal RequestId : ${requestId}`);
  console.log('╚══════════════════════════════════════════════════════════╝');
  console.log(`[${requestId}] Method  : ${req.method}`);
  console.log(`[${requestId}] URL     : ${req.originalUrl}`);
  console.log(`[${requestId}] IP      : ${req.ip || req.connection?.remoteAddress}`);
  console.log(`[${requestId}] Body    : ${JSON.stringify(req.body, null, 2)}`);

  // ── STEP 1: EXTRACT & VALIDATE REQUEST BODY ───────────────────────────────
  console.log(`\n[${requestId}] ── STEP 1: Extracting fields from request body...`);

  const { pnr, lastName } = req.body;

  const missingFields = [];
  if (!pnr)      missingFields.push('pnr');
  if (!lastName) missingFields.push('lastName');

  if (missingFields.length > 0) {
    console.warn(`[${requestId}] ✗ VALIDATION FAILED — Missing: [${missingFields.join(', ')}]`);
    return res.status(400).json({
      success: false,
      requestId,
      error:   'Validation Error',
      message: `Missing required field(s): ${missingFields.join(', ')}`,
      missingFields,
    });
  }

  console.log(`[${requestId}] ✓ pnr      : ${pnr}`);
  console.log(`[${requestId}] ✓ lastName : ${lastName}`);

  // ── STEP 2: SERVER CONFIG VALIDATION ─────────────────────────────────────
  console.log(`\n[${requestId}] ── STEP 2: Validating server config...`);

  const missingEnvVars = [];
  if (!ENV_TARGET_BRANCH) missingEnvVars.push('TARGET_BRANCH');
  if (!ENV_PROVIDER_CODE) missingEnvVars.push('PROVIDER_CODE');

  if (missingEnvVars.length > 0) {
    console.error(`[${requestId}] ✗ SERVER CONFIG ERROR — missing .env vars: [${missingEnvVars.join(', ')}]`);
    return res.status(500).json({
      success: false,
      requestId,
      error:   'Server Configuration Error',
      message: `Server is missing required .env variable(s): ${missingEnvVars.join(', ')}`,
      missingEnvVars,
    });
  }

  console.log(`[${requestId}] ✓ Server config valid.`);

  // ── STEP 3: QUERY uflights TABLE ──────────────────────────────────────────
  console.log(`\n[${requestId}] ── STEP 3: Querying uflights table for PNR: "${pnr}"...`);

  let flightRecord;
  try {
    const [rows] = await db.query(
      `SELECT booking_id, UniversalLocator, AirReservationLocator, GdsLocator, Status
       FROM uflights
       WHERE AirReservationLocator = ?
       LIMIT 1`,
      [pnr]
    );

    // PNR not found
    if (!rows || rows.length === 0) {
      console.warn(`[${requestId}] ✗ PNR "${pnr}" not found in uflights.`);
      return res.status(404).json({
        success: false,
        requestId,
        error:   'Not Found',
        message: `PNR "${pnr}" not found.`,
      });
    }

    flightRecord = rows[0];
    console.log(`[${requestId}] ✓ Flight record found:`);
    console.log(`[${requestId}]   booking_id             : ${flightRecord.booking_id}`);
    console.log(`[${requestId}]   UniversalLocator       : ${flightRecord.UniversalLocator}`);
    console.log(`[${requestId}]   AirReservationLocator  : ${flightRecord.AirReservationLocator}`);
    console.log(`[${requestId}]   GdsLocator             : ${flightRecord.GdsLocator}`);
    console.log(`[${requestId}]   Status                 : ${flightRecord.Status}`);

    // Status check — must be exactly 'ticketed' (case insensitive)
    if (!flightRecord.Status || flightRecord.Status.toLowerCase() !== 'ticketed') {
      console.warn(`[${requestId}] ✗ Booking status is "${flightRecord.Status}" — not Ticketed.`);
      return res.status(400).json({
        success: false,
        requestId,
        error:   'Booking Not Ticketed',
        message: `This booking is currently "${flightRecord.Status}". Only ticketed bookings can retrieve documents.`,
        status:  flightRecord.Status,
      });
    }

    console.log(`[${requestId}] ✓ Status is "ticketed" — proceeding.`);

  } catch (dbError) {
    console.error(`[${requestId}] ✗ DB ERROR (uflights): ${dbError.message}`);
    return res.status(500).json({
      success: false,
      requestId,
      error:   'Database Error',
      message: 'Failed to query flight records.',
    });
  }

  // ── STEP 4: QUERY PassengersDetails TABLE ─────────────────────────────────
  console.log(`\n[${requestId}] ── STEP 4: Querying PassengersDetails for booking_id: ${flightRecord.booking_id}, lastName: "${lastName}"...`);

  let passengers;
  try {
    const [rows] = await db.query(
      `SELECT passenger_id, first_name, last_name, ticket_number
       FROM PassengersDetails
       WHERE booking_id = ?
       AND LOWER(last_name) = LOWER(?)`,
      [flightRecord.booking_id, lastName]
    );

    if (!rows || rows.length === 0) {
      console.warn(`[${requestId}] ✗ No passenger found with lastName "${lastName}" for booking_id ${flightRecord.booking_id}`);
      return res.status(404).json({
        success: false,
        requestId,
        error:   'Not Found',
        message: `No passenger found with last name "${lastName}" for the given PNR.`,
      });
    }

    passengers = rows;
    console.log(`[${requestId}] ✓ ${passengers.length} passenger(s) found with lastName "${lastName}"`);
    passengers.forEach((p, i) => {
      console.log(`[${requestId}]   [${i + 1}] passenger_id: ${p.passenger_id} | name: ${p.first_name} ${p.last_name} | ticket: ${p.ticket_number}`);
    });

  } catch (dbError) {
    console.error(`[${requestId}] ✗ DB ERROR (PassengersDetails): ${dbError.message}`);
    return res.status(500).json({
      success: false,
      requestId,
      error:   'Database Error',
      message: 'Failed to query passenger records.',
    });
  }

  // ── STEP 5: CALL AirRetrieveDocumentService FOR EACH TICKET ───────────────
  console.log(`\n[${requestId}] ── STEP 5: Calling AirRetrieveDocumentService for ${passengers.length} ticket(s)...`);

  const traceId = generateTraceId();
  const results = [];

  for (let i = 0; i < passengers.length; i++) {
    const passenger    = passengers[i];
    const ticketNumber = passenger.ticket_number;

    console.log(`\n[${requestId}]   [Ticket ${i + 1}/${passengers.length}] ticket_number: ${ticketNumber}`);

    // Skip if ticket number is missing
    if (!ticketNumber) {
      console.warn(`[${requestId}]   [Ticket ${i + 1}] ✗ ticket_number is null/empty — skipping.`);
      results.push({
        passenger_id: passenger.passenger_id,
        name:         `${passenger.first_name} ${passenger.last_name}`,
        ticketNumber: null,
        success:      false,
        error:        'Ticket number not found for this passenger.',
      });
      continue;
    }

    // Build payload
    const servicePayload = {
      traceId,
      targetBranch:         ENV_TARGET_BRANCH,
      authorizedBy:         ENV_AUTHORIZED_BY,
      providerCode:         ENV_PROVIDER_CODE,
      providerLocatorCode:  flightRecord.UniversalLocator,
      ticketNumber,
      returnRestrictions:   true,
      returnPricing:        true,
      retrieveMCO:          true,
      retrieveAgencyInfo:   false,
      retrieveCannedRemark: false,
      originApplication:    'Travel',
      ...(flightRecord.AirReservationLocator
        ? { airReservationLocatorCode: flightRecord.AirReservationLocator }
        : {}),
    };

    console.log(`[${requestId}]   [Ticket ${i + 1}] Service payload: ${JSON.stringify(servicePayload, null, 2)}`);

    try {
      const result = await airRetrieveDocumentService.retrieveDocument(servicePayload, requestId);
      const { _raw, ...cleanResult } = result;

      console.log(`[${requestId}]   [Ticket ${i + 1}] ✓ Success`);
      results.push({
        passenger_id: passenger.passenger_id,
        name:         `${passenger.first_name} ${passenger.last_name}`,
        ticketNumber,
        success:      true,
        data:         cleanResult,
      });

    } catch (error) {
      console.error(`[${requestId}]   [Ticket ${i + 1}] ✗ Error: ${error.message}`);

      results.push({
        passenger_id: passenger.passenger_id,
        name:         `${passenger.first_name} ${passenger.last_name}`,
        ticketNumber,
        success:      false,
        error:        error.isSoapFault
          ? { type: 'SOAP Fault', faultCode: error.faultCode, faultString: error.faultString }
          : { type: 'Service Error', message: error.message },
      });
    }
  }

  // ── STEP 6: SEND RESPONSE ─────────────────────────────────────────────────
  const totalDuration = Date.now() - requestStartTime;
  const successCount  = results.filter(r => r.success).length;

  console.log(`\n[${requestId}] ── STEP 6: Sending response...`);
  console.log(`[${requestId}] Total tickets : ${passengers.length}`);
  console.log(`[${requestId}] Successful    : ${successCount}`);
  console.log(`[${requestId}] Failed        : ${passengers.length - successCount}`);
  console.log(`[${requestId}] Total duration: ${totalDuration}ms`);
  console.log('╔══════════════════════════════════════════════════════════╗');
  console.log(`║  [${requestId}] COMPLETE — ${totalDuration}ms`);
  console.log('╚══════════════════════════════════════════════════════════╝\n');

  return res.status(200).json({
    success:      true,
    requestId,
    traceId,
    durationMs:   totalDuration,
    pnr,
    totalTickets: passengers.length,
    successCount,
    failedCount:  passengers.length - successCount,
    results,
  });
};

module.exports = retrieveDocument;