import {
  compareHotelStays,
  sortDayItems,
  sortHotelStays,
  sortItineraryRows,
} from './itinerary-order';

describe('itinerary-order', () => {
  describe('sortHotelStays', () => {
    it('orders stays by check-in date (reported Copy Email case)', () => {
      const stays = [
        { name: 'Millennium', check_in_date: '2027-01-01', check_out_date: '2027-01-02' },
        { name: 'Omega', check_in_date: '2026-12-27', check_out_date: '2027-01-01' },
      ];
      expect(sortHotelStays(stays).map((s) => s.name)).toEqual(['Omega', 'Millennium']);
      // input untouched
      expect(stays[0].name).toBe('Millennium');
    });

    it('breaks a same check-in tie by check-out date, keeps full ties stable', () => {
      const stays = [
        { name: 'C', check_in_date: '2026-12-27', check_out_date: '2026-12-30' },
        { name: 'A', check_in_date: '2026-12-27', check_out_date: '2026-12-28' },
        { name: 'D', check_in_date: '2026-12-27', check_out_date: '2026-12-30' },
      ];
      expect(sortHotelStays(stays).map((s) => s.name)).toEqual(['A', 'C', 'D']);
    });

    it('puts stays without a check-in last', () => {
      expect(
        compareHotelStays({ check_in_date: null }, { check_in_date: '2026-12-27' }),
      ).toBeGreaterThan(0);
    });
  });

  describe('sortDayItems', () => {
    it('orders by date, then sort_order, undated last', () => {
      const items = [
        { id: 'undated', date: null, sort_order: 0 },
        { id: 'd2', date: '2026-12-29', sort_order: 0 },
        { id: 'd1-b', date: '2026-12-28', sort_order: 2 },
        { id: 'd1-a', date: '2026-12-28', sort_order: 1 },
      ];
      expect(sortDayItems(items).map((i) => i.id)).toEqual(['d1-a', 'd1-b', 'd2', 'undated']);
    });
  });

  describe('sortItineraryRows', () => {
    it('sorts every row list in place and skips missing lists', () => {
      const target = {
        hotel_items: [
          { check_in_date: '2027-01-01', check_out_date: '2027-01-02' },
          { check_in_date: '2026-12-27', check_out_date: '2027-01-01' },
        ],
        transport_items: [
          { date: '2026-12-30', sort_order: 0 },
          { date: '2026-12-27', sort_order: 0 },
        ],
        activity_items: undefined,
      };
      sortItineraryRows(target);
      expect(target.hotel_items.map((h) => h.check_in_date)).toEqual(['2026-12-27', '2027-01-01']);
      expect(target.transport_items.map((t) => t.date)).toEqual(['2026-12-27', '2026-12-30']);
      expect(target.activity_items).toBeUndefined();
    });
  });
});
