import { In, type Repository } from 'typeorm';
import type { ClsService } from 'nestjs-cls';
import { TransportPricingRepository } from './transport-pricing.repository';
import { TransportPricingEntity } from '../../../entities/transport-pricing.entity';
import { CLS_TENANT_ID } from '../../../common/cls/cls.constants';

/**
 * findPaginatedByRoutes — vehicle types + mode ("without SIC") filters.
 * The query builder is a chainable mock that records every andWhere so
 * we can assert the filters reach both the count and the page query.
 */
function makeQb(raw: { one?: unknown; many?: unknown[] }) {
  const qb: Record<string, jest.Mock> = {};
  const chain = () => qb;
  for (const m of [
    'select',
    'addSelect',
    'where',
    'andWhere',
    'leftJoin',
    'groupBy',
    'orderBy',
    'addOrderBy',
    'offset',
    'limit',
  ]) {
    qb[m] = jest.fn(chain);
  }
  qb.getRawOne = jest.fn().mockResolvedValue(raw.one);
  qb.getRawMany = jest.fn().mockResolvedValue(raw.many ?? []);
  return qb;
}

describe('TransportPricingRepository.findPaginatedByRoutes', () => {
  const TENANT_ID = 'tenant-1';
  const VT_ID = '11111111-1111-4111-8111-111111111111';
  const VT_ID_2 = '22222222-2222-4222-8222-222222222222';
  let countQb: ReturnType<typeof makeQb>;
  let routeQb: ReturnType<typeof makeQb>;
  let ormRepo: { createQueryBuilder: jest.Mock; find: jest.Mock };
  let cls: { get: jest.Mock };
  let repo: TransportPricingRepository;

  beforeEach(() => {
    countQb = makeQb({ one: { count: '1' } });
    routeQb = makeQb({ many: [{ transport_service_id: 'svc-1' }] });
    ormRepo = {
      createQueryBuilder: jest.fn().mockReturnValueOnce(countQb).mockReturnValueOnce(routeQb),
      find: jest.fn().mockResolvedValue([{ id: 'row-1' }]),
    };
    cls = { get: jest.fn((key: string) => (key === CLS_TENANT_ID ? TENANT_ID : undefined)) };
    repo = new TransportPricingRepository(
      ormRepo as unknown as Repository<TransportPricingEntity>,
      cls as unknown as ClsService,
    );
  });

  afterEach(() => jest.clearAllMocks());

  const whereArgs = (qb: ReturnType<typeof makeQb>) =>
    qb.andWhere.mock.calls.map((c: unknown[]) => c[0]);

  it('applies the vehicle type list to the route count, route page and row fetch', async () => {
    await repo.findPaginatedByRoutes({ vehicleTypeIds: [VT_ID, VT_ID_2] });

    for (const qb of [countQb, routeQb]) {
      expect(qb.andWhere).toHaveBeenCalledWith('tp.vehicle_type_id IN (:...vehicleTypeIds)', {
        vehicleTypeIds: [VT_ID, VT_ID_2],
      });
    }
    const where = ormRepo.find.mock.calls[0][0].where;
    expect(where).toEqual([
      expect.objectContaining({
        transport_service_id: 'svc-1',
        vehicle_type_id: In([VT_ID, VT_ID_2]),
      }),
    ]);
  });

  it('treats an empty vehicle type list as no filter', async () => {
    await repo.findPaginatedByRoutes({ vehicleTypeIds: [] });
    expect(whereArgs(countQb)).not.toContain('tp.vehicle_type_id IN (:...vehicleTypeIds)');
    expect(ormRepo.find.mock.calls[0][0].where[0]).not.toHaveProperty('vehicle_type_id');
  });

  it('mode=PVT ("without SIC") filters out SIC rows at every step', async () => {
    await repo.findPaginatedByRoutes({ mode: 'PVT' });

    expect(countQb.andWhere).toHaveBeenCalledWith('tp.mode = :mode', { mode: 'PVT' });
    expect(routeQb.andWhere).toHaveBeenCalledWith('tp.mode = :mode', { mode: 'PVT' });
    expect(ormRepo.find.mock.calls[0][0].where[0]).toEqual(
      expect.objectContaining({ mode: 'PVT' }),
    );
  });

  it('adds no vehicle / mode clauses when the filters are omitted', async () => {
    await repo.findPaginatedByRoutes({});

    for (const qb of [countQb, routeQb]) {
      expect(whereArgs(qb)).not.toContain('tp.vehicle_type_id IN (:...vehicleTypeIds)');
      expect(whereArgs(qb)).not.toContain('tp.mode = :mode');
    }
    const row = ormRepo.find.mock.calls[0][0].where[0];
    expect(row).not.toHaveProperty('vehicle_type_id');
    expect(row).not.toHaveProperty('mode');
  });

  it('scopes every query to the CLS tenant (tenant isolation)', async () => {
    await repo.findPaginatedByRoutes({ vehicleTypeIds: [VT_ID], mode: 'PVT' });

    expect(countQb.where).toHaveBeenCalledWith(
      'tp.tenant_id = :tenantId AND tp.is_deleted = false',
      { tenantId: TENANT_ID },
    );
    expect(routeQb.where).toHaveBeenCalledWith(
      'tp.tenant_id = :tenantId AND tp.is_deleted = false',
      { tenantId: TENANT_ID },
    );
    expect(ormRepo.find.mock.calls[0][0].where[0]).toEqual(
      expect.objectContaining({ tenant_id: TENANT_ID }),
    );
  });

  it('refuses to query when CLS has no tenant (no cross-tenant fallback)', async () => {
    cls.get.mockReturnValue(undefined);
    await expect(repo.findPaginatedByRoutes({ mode: 'PVT' })).rejects.toThrow();
    expect(ormRepo.find).not.toHaveBeenCalled();
  });
});
