/**
 * Resolves a booking's actual boarding/alighting station AND time for one leg from
 * originStationId/destinationStationId (set when the booking covers only part of a
 * longer multi-stop schedule, e.g. train runs A→D but the passenger booked B→D), via
 * the schedule's stopTimes — falling back to the schedule's own full-route
 * station/time when there's no segment override (older records, or a booking that
 * covers the whole run).
 *
 * Single source of truth for this resolution — station-only lookups used to be
 * duplicated ad hoc across bookings/tickets/notifications while the departureAt/
 * arrivalAt kept being read straight off the schedule (the train's full-route span),
 * which showed the wrong boarding/alighting time for any stop-based booking.
 */
export interface ResolvedSegment {
  origin: any;
  destination: any;
  departureAt: any;
  arrivalAt: any;
}

export function resolveBookingSegment(
  schedule: any,
  originStationId: string | null | undefined,
  destinationStationId: string | null | undefined,
): ResolvedSegment {
  const stopTimes: any[] = schedule?.stopTimes ?? [];
  const findStop = (stationId: string | null | undefined) =>
    stationId && stopTimes.length > 0 ? stopTimes.find((st: any) => st.stationId === stationId) : undefined;
  const originStop = findStop(originStationId);
  const destStop = findStop(destinationStationId);
  return {
    origin: originStop?.station ?? schedule?.originStation ?? null,
    destination: destStop?.station ?? schedule?.destinationStation ?? null,
    departureAt: originStop?.plannedDepartureAt ?? schedule?.departureAt ?? null,
    arrivalAt: destStop?.plannedArrivalAt ?? schedule?.arrivalAt ?? null,
  };
}
