import { BookingContextResolver } from './booking-context.resolver';

describe('BookingContextResolver — itinerary order', () => {
  const TENANT = 'tenant-a';
  const booking = {
    id: 'b1',
    booking_number: 'BK-1',
    tenant_id: TENANT,
    selling_total: 8272,
    query: {
      start_date: '2026-12-27',
      end_date: '2027-01-02',
      adults: 2,
      destination: { name: 'Dubai' },
    },
    // Relation order as loaded — NOT chronological.
    hotel_items: [
      {
        id: 'h2',
        check_in_date: '2027-01-01',
        check_out_date: '2027-01-02',
        nights: 1,
        selected_nights: [5],
        periods: [],
        hotel: { name: 'Millennium Downtown Abu Dhabi', destination: { name: 'Dubai' } },
      },
      {
        id: 'h1',
        check_in_date: '2026-12-27',
        check_out_date: '2027-01-01',
        nights: 5,
        selected_nights: [0, 1, 2, 3, 4],
        periods: [],
        hotel: { name: 'Omega, Bur Dubai', destination: { name: 'Dubai' } },
      },
    ],
    transport_items: [
      {
        id: 't2',
        date: '2026-12-27',
        sort_order: 2,
        transport_service: { from_city: 'Hotel', to_city: 'Mall' },
      },
      {
        id: 't1',
        date: '2026-12-27',
        sort_order: 1,
        transport_service: { from_city: 'Airport', to_city: 'Hotel' },
      },
    ],
    activity_items: [],
    special_items: [],
  };

  const bookings = { findOne: jest.fn() };
  const tenantSettings = { findOne: jest.fn().mockResolvedValue({ company_name: 'Co' }) };
  const users = { findOne: jest.fn().mockResolvedValue(null) };
  const destinations = { manager: { query: jest.fn().mockResolvedValue([]) } };
  const cls = { get: jest.fn().mockReturnValue(TENANT) };

  const resolver = new BookingContextResolver(
    bookings as any,
    tenantSettings as any,
    users as any,
    destinations as any,
    cls as any,
  );

  beforeEach(() => bookings.findOne.mockResolvedValue(structuredClone(booking)));
  afterEach(() => jest.clearAllMocks());

  it('lists Copy Email hotels by check-in date', async () => {
    const data = await resolver.build('b1');
    const hotels = data.hotels as Array<{ hotel_name: string; nights: number }>;
    expect(hotels.map((h) => h.hotel_name)).toEqual([
      'Omega, Bur Dubai',
      'Millennium Downtown Abu Dhabi',
    ]);
  });

  it('prints a day’s transfers in row order in the WA day blocks', async () => {
    const data = await resolver.build('b1');
    const block = data.day_blocks as string;
    expect(block.indexOf('Airport → Hotel')).toBeLessThan(block.indexOf('Hotel → Mall'));
  });

  it('scopes the booking lookup to the CLS tenant', async () => {
    await resolver.build('b1');
    expect(bookings.findOne).toHaveBeenCalledWith(
      expect.objectContaining({ where: expect.objectContaining({ id: 'b1', tenant_id: TENANT }) }),
    );
  });
});
