import {
  detectBookingApprovalTriggers,
  detectBookedTicketChange,
  detectWithinWindow,
  loadApprovalContext,
  SavedActivityLine,
} from './booking-approval-triggers';
import { ChangeRequestKind } from '../../entities/booking-change-request.entity';
import { BookingStatus } from '../../entities/booking.entity';

describe('booking-approval-triggers', () => {
  // 5 Nov 2026, 10:00 UTC → 14:00 in Dubai (still 5 Nov).
  beforeAll(() => {
    jest.useFakeTimers();
    jest.setSystemTime(new Date('2026-11-05T10:00:00Z'));
  });
  afterAll(() => jest.useRealTimers());

  const TZ = 'Asia/Dubai';

  describe('detectWithinWindow', () => {
    it('window 2 on 5 Nov: trip on 7 Nov needs approval', () => {
      expect(detectWithinWindow('2026-11-07', TZ, 2)?.kind).toBe(
        ChangeRequestKind.NEXT_DAY_BOOKING,
      );
    });

    it('window 2 on 5 Nov: trip on 8 Nov is free', () => {
      expect(detectWithinWindow('2026-11-08', TZ, 2)).toBeNull();
    });

    it('trip today is same-day', () => {
      expect(detectWithinWindow('2026-11-05', TZ, 2)?.kind).toBe(
        ChangeRequestKind.SAME_DAY_BOOKING,
      );
    });

    it('trip already started needs approval', () => {
      expect(detectWithinWindow('2026-11-01', TZ, 2)?.kind).toBe(
        ChangeRequestKind.SAME_DAY_BOOKING,
      );
    });

    it('on-trip status always needs approval', () => {
      expect(detectWithinWindow('2026-12-20', TZ, 2, BookingStatus.ONGOING)?.kind).toBe(
        ChangeRequestKind.SAME_DAY_BOOKING,
      );
    });

    it('window 0 only catches today', () => {
      expect(detectWithinWindow('2026-11-06', TZ, 0)).toBeNull();
      expect(detectWithinWindow('2026-11-05', TZ, 0)).not.toBeNull();
    });

    it('uses the destination timezone for "today"', () => {
      // 22:00 UTC on 5 Nov is already 6 Nov in Dubai.
      jest.setSystemTime(new Date('2026-11-05T22:00:00Z'));
      expect(detectWithinWindow('2026-11-08', TZ, 2)).not.toBeNull();
      jest.setSystemTime(new Date('2026-11-05T10:00:00Z'));
    });

    it('missing start date never blocks', () => {
      expect(detectWithinWindow(null, TZ, 2)).toBeNull();
    });
  });

  describe('detectBookedTicketChange', () => {
    const booked: SavedActivityLine = {
      id: 'a1',
      activity_id: 'act-1',
      ticket_id: 't-1',
      age_group: 'adult',
      quantity: 2,
      unit_price: '150.00',
      date: '2026-12-20',
      slot: null,
      supplier_id: null,
      notes: null,
      ticket_status: 'Booked',
    };
    const pending: SavedActivityLine = { ...booked, id: 'a2', ticket_status: 'Pending' };
    const same = (a: SavedActivityLine) => ({
      id: a.id,
      activity_id: a.activity_id,
      ticket_id: a.ticket_id,
      age_group: a.age_group,
      quantity: Number(a.quantity),
      unit_price: Number(a.unit_price),
      date: a.date as string,
    });

    it('unchanged booked line is free', () => {
      expect(detectBookedTicketChange([booked], { activity_items: [same(booked)] })).toBeNull();
    });

    it.each([
      ['quantity', { quantity: 3 }],
      ['date', { date: '2026-12-21' }],
      ['price', { unit_price: 160 }],
      ['ticket', { ticket_id: 't-2' }],
      ['activity', { activity_id: 'act-2' }],
    ])('changing the %s of a booked line needs approval', (_label, patch) => {
      const r = detectBookedTicketChange([booked], {
        activity_items: [{ ...same(booked), ...patch }],
      });
      expect(r?.kind).toBe(ChangeRequestKind.POST_CONFIRM_EDIT);
    });

    it('removing a booked line needs approval', () => {
      expect(detectBookedTicketChange([booked], { activity_items: [] })).not.toBeNull();
    });

    it('On Hold counts as booked', () => {
      const held = { ...booked, ticket_status: 'On Hold' };
      expect(detectBookedTicketChange([held], { activity_items: [] })).not.toBeNull();
    });

    it('changing a Pending ticket line is free', () => {
      expect(
        detectBookedTicketChange([booked, pending], {
          activity_items: [same(booked), { ...same(pending), quantity: 5 }],
        }),
      ).toBeNull();
    });

    it('adding a new activity is free', () => {
      expect(
        detectBookedTicketChange([booked], {
          activity_items: [same(booked), { activity_id: 'act-9', quantity: 1 }],
        }),
      ).toBeNull();
    });

    it('payload without activity_items (hotel/transfer-only save) is free', () => {
      expect(detectBookedTicketChange([booked], {})).toBeNull();
    });

    it('legacy payload without ids matches on activity|ticket|date|age', () => {
      const { id: _id, ...noId } = same(booked);
      void _id;
      expect(detectBookedTicketChange([booked], { activity_items: [noId] })).toBeNull();
      expect(
        detectBookedTicketChange([booked], {
          activity_items: [{ ...noId, date: '2026-12-22' }],
        }),
      ).not.toBeNull();
    });
  });

  describe('detectBookingApprovalTriggers', () => {
    const booked: SavedActivityLine = {
      id: 'a1',
      activity_id: 'act-1',
      ticket_status: 'Booked',
      date: '2026-12-20',
    };

    it('December trip, hotel/transfer change → no approval', () => {
      expect(
        detectBookingApprovalTriggers({
          startDate: '2026-12-20',
          destTz: TZ,
          windowDays: 2,
          currentStatus: BookingStatus.UPCOMING,
          savedActivities: [booked],
          dto: { activity_items: [{ id: 'a1', activity_id: 'act-1' }] },
        }),
      ).toEqual([]);
    });

    it('December trip, booked ticket removed → booked-ticket rule', () => {
      const [t] = detectBookingApprovalTriggers({
        startDate: '2026-12-20',
        destTz: TZ,
        windowDays: 2,
        savedActivities: [booked],
        dto: { activity_items: [] },
      });
      expect(t.kind).toBe(ChangeRequestKind.POST_CONFIRM_EDIT);
    });

    it('inside the window → window rule (one trigger only)', () => {
      const r = detectBookingApprovalTriggers({
        startDate: '2026-11-06',
        destTz: TZ,
        windowDays: 2,
        savedActivities: [booked],
        dto: { activity_items: [] },
      });
      expect(r).toHaveLength(1);
      expect(r[0].kind).toBe(ChangeRequestKind.NEXT_DAY_BOOKING);
    });

    it('admin-set window of 60 days catches December', () => {
      expect(
        detectBookingApprovalTriggers({ startDate: '2026-12-20', destTz: TZ, windowDays: 60 }),
      ).toHaveLength(1);
    });
  });

  describe('loadApprovalContext', () => {
    it('scopes both queries to the tenant', async () => {
      const query = jest
        .fn()
        .mockResolvedValueOnce([{ approval_window_days: 4 }])
        .mockResolvedValueOnce([]);
      const ctx = await loadApprovalContext({ query } as any, 'tenant-A', 'b1');
      expect(ctx.windowDays).toBe(4);
      expect(query.mock.calls[0][0]).toMatch(/tenant_id = \$1/);
      expect(query.mock.calls[0][1]).toEqual(['tenant-A']);
      expect(query.mock.calls[1][0]).toMatch(/tenant_id = \$2/);
      expect(query.mock.calls[1][1]).toEqual(['b1', 'tenant-A']);
    });

    it("does not return another tenant's lines (rows come only from the scoped query)", async () => {
      const query = jest.fn().mockResolvedValueOnce([]).mockResolvedValueOnce([]);
      const ctx = await loadApprovalContext({ query } as any, 'tenant-B', 'b-of-tenant-A');
      expect(ctx.savedActivities).toEqual([]);
      expect(query.mock.calls[1][1]).toEqual(['b-of-tenant-A', 'tenant-B']);
    });

    it('falls back to 2 days when settings are missing', async () => {
      const query = jest.fn().mockResolvedValueOnce([]).mockResolvedValueOnce([]);
      const ctx = await loadApprovalContext({ query } as any, 't', 'b');
      expect(ctx.windowDays).toBe(2);
    });
  });
});
