/**
 * Chronological order for itinerary rows — one rule for every output
 * (booking/quote detail, Copy Email / Copy WA templates, invoices).
 *
 * Hotels: check-in date, then check-out date (shorter stay first).
 * Day items (transport / activity / special): date, then the day's
 * row order (`sort_order`). Undated rows go last.
 *
 * Both return a new array; ties keep their input order (stable sort).
 */

interface HotelStayLike {
  check_in_date?: string | null;
  check_out_date?: string | null;
}

interface DayItemLike {
  date?: string | null;
  sort_order?: number | null;
}

const LAST_DATE = '9999-12-31';

export function compareHotelStays(a: HotelStayLike, b: HotelStayLike): number {
  return (
    (a.check_in_date || LAST_DATE).localeCompare(b.check_in_date || LAST_DATE) ||
    (a.check_out_date || LAST_DATE).localeCompare(b.check_out_date || LAST_DATE)
  );
}

export function sortHotelStays<T extends HotelStayLike>(items: readonly T[]): T[] {
  return [...items].sort(compareHotelStays);
}

export function sortDayItems<T extends DayItemLike>(items: readonly T[]): T[] {
  return [...items].sort(
    (a, b) =>
      (a.date || LAST_DATE).localeCompare(b.date || LAST_DATE) ||
      (a.sort_order ?? 999) - (b.sort_order ?? 999),
  );
}

interface ItineraryRowsLike {
  hotel_items?: HotelStayLike[] | null;
  transport_items?: DayItemLike[] | null;
  activity_items?: DayItemLike[] | null;
  special_items?: DayItemLike[] | null;
}

/** Puts a booking's / quote's loaded line items in chronological order
 *  (in place). TypeORM relations load in arbitrary order. */
export function sortItineraryRows(target: ItineraryRowsLike): void {
  if (Array.isArray(target.hotel_items)) target.hotel_items = sortHotelStays(target.hotel_items);
  for (const key of ['transport_items', 'activity_items', 'special_items'] as const) {
    const rows = target[key];
    if (Array.isArray(rows)) target[key] = sortDayItems(rows);
  }
}
