import { matchUnlinkedFlights } from './flight-match';

describe('matchUnlinkedFlights', () => {
  const rows = [
    { id: 'arr', date: '2026-10-13' },
    { id: 'dep', date: '2026-10-21' },
  ];

  it('puts arrival and departure on their own transfers', () => {
    const m = matchUnlinkedFlights(
      rows,
      [
        { direction: 'Arrival', arrival_time: '2026-10-13T12:45' },
        // 02:50 flight — transfer is the evening before
        { direction: 'Departure', departure_time: '2026-10-22T02:50' },
      ],
      new Set(),
    );
    expect(m.get('arr')?.arrival_time).toBe('2026-10-13T12:45');
    expect(m.get('dep')?.departure_time).toBe('2026-10-22T02:50');
  });

  it('falls back to earliest / latest row when dates do not match', () => {
    const m = matchUnlinkedFlights(
      rows,
      [
        { direction: 'Departure', departure_time: null },
        { direction: 'Arrival', arrival_time: null },
      ],
      new Set(),
    );
    expect(m.get('arr')?.direction).toBe('Arrival');
    expect(m.get('dep')?.direction).toBe('Departure');
  });

  it('never reuses a row already linked to a flight', () => {
    const m = matchUnlinkedFlights(
      rows,
      [{ direction: 'Arrival', arrival_time: '2026-10-13T12:45' }],
      new Set(['arr']),
    );
    expect(m.has('arr')).toBe(false);
    expect(m.get('dep')?.direction).toBe('Arrival');
  });

  it('matches a flight with no direction only by date or 1:1', () => {
    expect(
      matchUnlinkedFlights(rows, [{ arrival_time: '2026-10-21T09:00' }], new Set()).has('dep'),
    ).toBe(true);
    expect(matchUnlinkedFlights(rows, [{ arrival_time: 'not-a-date' }], new Set()).size).toBe(0);
    expect(
      matchUnlinkedFlights([{ id: 'only', date: '2026-10-13' }], [{}], new Set()).has('only'),
    ).toBe(true);
  });

  it('accepts Date objects from the driver', () => {
    const m = matchUnlinkedFlights(
      [{ id: 'r', date: new Date(2026, 9, 13) }],
      [{ direction: 'Arrival', arrival_time: '2026-10-13T08:00' }],
      new Set(),
    );
    expect(m.has('r')).toBe(true);
  });
});
