import {
  activityLineKey,
  orderActivityRowsOwnerFirst,
  pickActivityLineOwner,
} from './activity-line-owner';

const row = (id: string, age_group: string, extra: Record<string, unknown> = {}) => ({
  id,
  age_group,
  booking_id: 'b1',
  activity_id: 'a1',
  ticket_id: null,
  date: '2026-11-01',
  sort_order: 0,
  ...extra,
});

describe('activity line owner', () => {
  it('prefers the row that owns the junction rows', () => {
    const rows = [row('a', 'adult'), row('c', 'child')];
    const owner = pickActivityLineOwner(rows, (id) => (id === 'c' ? 2 : 0));
    expect(owner.id).toBe('c');
  });

  it('falls back to adult → senior → child, then lowest id', () => {
    expect(pickActivityLineOwner([row('z', 'child'), row('y', 'adult')], () => 0).id).toBe('y');
    expect(pickActivityLineOwner([row('z', 'child'), row('y', 'senior')], () => 0).id).toBe('y');
    expect(pickActivityLineOwner([row('b', 'adult'), row('a', 'adult')], () => 0).id).toBe('a');
  });

  it('is the same whatever order the database returns', () => {
    const a = [row('1', 'child'), row('2', 'adult')];
    const b = [...a].reverse();
    expect(pickActivityLineOwner(a, () => 0).id).toBe(pickActivityLineOwner(b, () => 0).id);
  });

  it('puts each line owner first and keeps line order', () => {
    const rows = [row('c1', 'child'), row('x', 'adult', { booking_id: 'b2' }), row('a1', 'adult')];
    const ordered = orderActivityRowsOwnerFirst(rows, () => 0).map((r) => r.id);
    expect(ordered).toEqual(['a1', 'c1', 'x']);
  });

  it('keeps separate booking rows (sort_order) as separate lines', () => {
    expect(activityLineKey(row('1', 'adult'))).not.toBe(
      activityLineKey(row('2', 'adult', { sort_order: 1 })),
    );
  });
});
