import { BookingService } from './booking.service';

/**
 * attachBilledTotal — the AED (destination-currency) amount accounting
 * billed, shown under a USD price on the booking list.
 */
describe('BookingService.attachBilledTotal', () => {
  const query = jest.fn();
  // Bypass the constructor: only repo.ormRepo.manager and getTenantId are used.
  const service = Object.create(BookingService.prototype) as unknown as {
    attachBilledTotal: (rows: Array<Record<string, unknown>>) => Promise<void>;
  };
  Object.assign(service, {
    repo: { ormRepo: { manager: { query } } },
    getTenantId: () => 'tenant-a',
  });

  afterEach(() => query.mockReset());

  it('attaches the billed total per booking, tenant-filtered', async () => {
    query.mockResolvedValue([
      { booking_id: 'b1', currency_code: 'AED', currencies: '1', amount: '9847.00' },
      { booking_id: 'b2', currency_code: 'AED', currencies: '1', amount: '18913.384' },
    ]);
    const rows: Array<Record<string, unknown>> = [{ id: 'b1' }, { id: 'b2' }, { id: 'b3' }];
    await service.attachBilledTotal(rows);

    const [sql, params] = query.mock.calls[0];
    expect(sql).toContain('ps.tenant_id = $2');
    expect(params).toEqual([['b1', 'b2', 'b3'], 'tenant-a']);
    expect(rows[0].billed_total).toEqual({ amount: 9847, currency_code: 'AED' });
    expect(rows[1].billed_total).toEqual({ amount: 18913.38, currency_code: 'AED' });
    expect(rows[2].billed_total).toBeNull();
  });

  it('gives null when bills span several currencies', async () => {
    query.mockResolvedValue([
      { booking_id: 'b1', currency_code: 'AED', currencies: '2', amount: '100' },
    ]);
    const rows: Array<Record<string, unknown>> = [{ id: 'b1' }];
    await service.attachBilledTotal(rows);
    expect(rows[0].billed_total).toBeNull();
  });

  it('skips the query for an empty page', async () => {
    await service.attachBilledTotal([]);
    expect(query).not.toHaveBeenCalled();
  });

  it('never reads another tenant: the tenant id always comes from context', async () => {
    query.mockResolvedValue([]);
    await service.attachBilledTotal([{ id: 'b1', tenant_id: 'tenant-b' }]);
    expect(query.mock.calls[0][1][1]).toBe('tenant-a');
  });
});
