import { PaymentSettlementService } from './payment-settlement.service';
import { PaymentSettlementRepository } from './repositories/payment-settlement.repository';
import { BookingSettlementMasterRepository } from './repositories/booking-settlement-master.repository';
import { OverallSettlementStatus } from '../../entities/booking-settlement-master.entity';
import { CLS_TENANT_ID } from '../../common/cls/cls.constants';

/**
 * Settlements KPI strip follows every on-screen filter: date window,
 * destination, and — via matching booking ids — search + status.
 */
const clsFor = (tenantId: string) => ({
  get: (k: string) => (k === CLS_TENANT_ID ? tenantId : null),
});

describe('PaymentSettlementService.stats', () => {
  const run = (query: Parameters<PaymentSettlementService['stats']>[0]) => {
    const masters = { findBookingIdsForFilter: jest.fn().mockResolvedValue(['b1']) };
    const settlements = { statsForDashboard: jest.fn().mockResolvedValue({}) };
    const call = PaymentSettlementService.prototype.stats.call(
      { masters, settlements } as never,
      query,
    );
    return { masters, settlements, call };
  };

  it('uses only the window + destination when no search or status is sent', async () => {
    const { masters, settlements, call } = run({ from: '2026-11-01', to: '2026-11-30' });
    await call;
    expect(masters.findBookingIdsForFilter).not.toHaveBeenCalled();
    expect(settlements.statsForDashboard).toHaveBeenCalledWith(
      '2026-11-01',
      '2026-11-30',
      undefined,
      undefined,
    );
  });

  it('narrows to bookings matching the tab search', async () => {
    const { masters, settlements, call } = run({
      tab: 'agent',
      search: 'TravClan',
      from: '2026-11-01',
      to: '2026-11-30',
    });
    await call;
    expect(masters.findBookingIdsForFilter).toHaveBeenCalledWith({
      tab: 'agent',
      search: 'TravClan',
      status: undefined,
      destination_id: undefined,
      date_from: '2026-11-01',
      date_to: '2026-11-30',
    });
    expect(settlements.statsForDashboard).toHaveBeenCalledWith(
      '2026-11-01',
      '2026-11-30',
      undefined,
      ['b1'],
    );
  });

  it('narrows to bookings matching the status filter', async () => {
    const { masters, call } = run({ status: OverallSettlementStatus.PENDING });
    await call;
    expect(masters.findBookingIdsForFilter).toHaveBeenCalledWith(
      expect.objectContaining({ status: OverallSettlementStatus.PENDING }),
    );
  });

  it('ignores a whitespace-only search', async () => {
    const { masters, call } = run({ search: '   ' });
    await call;
    expect(masters.findBookingIdsForFilter).not.toHaveBeenCalled();
  });
});

describe('PaymentSettlementRepository.statsForDashboard — booking filter', () => {
  it('returns zeros without querying when no booking matches the filters', async () => {
    const createQueryBuilder = jest.fn();
    const query = jest.fn();
    const repo = new PaymentSettlementRepository(
      { createQueryBuilder, manager: { query } } as never,
      clsFor('t1') as never,
    );

    const res = await repo.statsForDashboard('2026-11-01', '2026-11-30', undefined, []);

    expect(createQueryBuilder).not.toHaveBeenCalled();
    expect(query).not.toHaveBeenCalled();
    expect(res).toMatchObject({
      pending_collections: 0,
      pending_refunds: 0,
      pending_supplier_payables: 0,
      settled_collections: 0,
      settled_refunds: 0,
    });
  });

  it('scopes every bucket to the tenant and the matching bookings', async () => {
    const andWhere = jest.fn();
    const qb: Record<string, jest.Mock> = {};
    for (const k of [
      'select',
      'addSelect',
      'where',
      'innerJoin',
      'leftJoin',
      'groupBy',
      'addGroupBy',
    ]) {
      qb[k] = jest.fn(() => qb);
    }
    qb.andWhere = andWhere.mockImplementation(() => qb);
    qb.getRawMany = jest.fn().mockResolvedValue([]);
    const query = jest.fn().mockResolvedValue([{ outstanding: '0', refund_due: '0' }]);
    const repo = new PaymentSettlementRepository(
      { createQueryBuilder: jest.fn(() => qb), manager: { query } } as never,
      clsFor('t1') as never,
    );

    await repo.statsForDashboard('2026-11-01', '2026-11-30', undefined, ['b1', 'b2']);

    expect(qb.where).toHaveBeenCalledWith('s.tenant_id = :tenantId', { tenantId: 't1' });
    expect(andWhere).toHaveBeenCalledWith('b.id IN (:...bookingIds)', {
      bookingIds: ['b1', 'b2'],
    });
    const [sql, params] = query.mock.calls[0] as [string, unknown[]];
    expect(sql).toContain('s.tenant_id = $1');
    expect(sql).toContain('b.id = ANY($4::uuid[])');
    expect(params).toEqual(['t1', '2026-11-01', '2026-11-30', ['b1', 'b2']]);
  });
});

describe('BookingSettlementMasterRepository.findBookingIdsForFilter', () => {
  const build = (tenantId: string) => {
    const query = jest.fn().mockResolvedValue([{ id: 'b1' }]);
    const repo = new BookingSettlementMasterRepository(
      { manager: { query } } as never,
      clsFor(tenantId) as never,
    );
    return { repo, query };
  };

  it('always scopes to the current tenant (no cross-tenant ids)', async () => {
    const { repo, query } = build('tenant-A');
    const ids = await repo.findBookingIdsForFilter({ tab: 'booking', search: 'x' });
    const [sql, params] = query.mock.calls[0] as [string, unknown[]];
    expect(sql).toContain('m.tenant_id = $1');
    expect(params[0]).toBe('tenant-A');
    expect(ids).toEqual(['b1']);
  });

  it('matches agent-tab search on the trip source name', async () => {
    const { repo, query } = build('t1');
    await repo.findBookingIdsForFilter({ tab: 'agent', search: 'TravClan' });
    const [sql, params] = query.mock.calls[0] as [string, unknown[]];
    expect(sql).toContain('ts.name ILIKE $2');
    expect(params).toEqual(['t1', '%TravClan%']);
  });

  it('applies status, destination and the trip-date window', async () => {
    const { repo, query } = build('t1');
    await repo.findBookingIdsForFilter({
      status: OverallSettlementStatus.PENDING,
      destination_id: 'd1',
      date_from: '2026-11-01',
      date_to: '2026-11-30',
    });
    const [sql, params] = query.mock.calls[0] as [string, unknown[]];
    expect(sql).toContain('m.overall_status = $2');
    expect(sql).toContain('q.destination_id = $3');
    expect(sql).toContain('q.start_date >= $4');
    expect(sql).toContain('q.start_date <= $5');
    expect(params).toEqual([
      't1',
      OverallSettlementStatus.PENDING,
      'd1',
      '2026-11-01',
      '2026-11-30',
    ]);
  });
});
