import type { ClsService } from 'nestjs-cls';
import type { Repository } from 'typeorm';
import type { AuditLogEntity } from '../../../entities/audit-log.entity';
import { AuditRepository } from './audit.repository';

const TENANT = 'tenant-a';
const SUP = '6ca033a8-2626-4c4c-a922-104bb899718f';
const DRV = '222085e7-6bb2-4fdb-91af-9df664338841';

function build(queryImpl: (sql: string, params: unknown[]) => unknown[] = () => []) {
  const query = jest.fn((sql: string, params: unknown[]) =>
    Promise.resolve(queryImpl(sql, params)),
  );
  const qb = {
    leftJoinAndSelect: jest.fn().mockReturnThis(),
    where: jest.fn().mockReturnThis(),
    andWhere: jest.fn().mockReturnThis(),
    orderBy: jest.fn().mockReturnThis(),
    skip: jest.fn().mockReturnThis(),
    take: jest.fn().mockReturnThis(),
    getManyAndCount: jest.fn().mockResolvedValue([[], 0]),
  };
  const orm = {
    manager: { query },
    createQueryBuilder: () => qb,
  } as unknown as Repository<AuditLogEntity>;
  const cls = { get: jest.fn().mockReturnValue(TENANT) } as unknown as ClsService;
  return { repo: new AuditRepository(orm, cls), query, qb };
}

const row = (entity_type: string, changes: AuditLogEntity['changes'] = null) =>
  ({ entity_type, entity_id: 'item-1', changes }) as AuditLogEntity;

describe('AuditRepository — readable audit', () => {
  it('scopes every list to the tenant; booking filter adds the booking trail', async () => {
    const { repo, qb } = build();
    await repo.findFiltered({ booking_ids: ['b-1'] });
    expect(qb.where).toHaveBeenCalledWith('a.tenant_id = :tenantId', { tenantId: TENANT });
    const [, params] = qb.andWhere.mock.calls[qb.andWhere.mock.calls.length - 1] as [
      unknown,
      Record<string, string>,
    ];
    expect(params).toEqual({ scopeBookingIds: ['b-1'] });
  });

  it('exact booking number wins, inside the tenant', async () => {
    const { repo, query } = build(() => [{ id: 'b-1' }]);
    expect(await repo.findBookingIdsByNumber(' mt-114473 ')).toEqual(['b-1']);
    expect(query).toHaveBeenCalledTimes(1);
    const [sql, params] = query.mock.calls[0];
    expect(sql).toContain('tenant_id = $1');
    expect(params).toEqual([TENANT, 'mt-114473']);
  });

  it('partial number → every matching booking (capped), tenant-scoped', async () => {
    const { repo, query } = build((sql) =>
      sql.includes('ILIKE') ? [{ id: 'b-1' }, { id: 'b-2' }] : [],
    );
    expect(await repo.findBookingIdsByNumber('1144')).toEqual(['b-1', 'b-2']);
    const [sql, params] = query.mock.calls[1];
    expect(sql).toContain('tenant_id = $1');
    expect(params).toEqual([TENANT, '%1144%', 20]);
  });

  it('escapes LIKE wildcards in the typed text', async () => {
    const { repo, query } = build(() => []);
    await repo.findBookingIdsByNumber('1_4%');
    expect(query.mock.calls[1][1][1]).toBe('%1\\_4\\%%');
  });

  it('resolves supplier / driver ids to names, tenant-scoped', async () => {
    const { repo, query } = build((sql) =>
      sql.includes('FROM suppliers')
        ? [{ id: SUP, label: 'Nexus Point' }]
        : sql.includes('FROM drivers')
          ? [{ id: DRV, label: 'Driver 6' }]
          : [],
    );
    const labels = await repo.loadValueLabels([
      row('booking_transport_item', [
        { field: 'supplier_id', old_value: null, new_value: SUP },
        { field: 'driver_id', old_value: DRV, new_value: null },
        { field: 'notes', old_value: SUP, new_value: 'x' },
      ]),
    ]);
    expect(labels.get(SUP)).toBe('Nexus Point');
    expect(labels.get(DRV)).toBe('Driver 6');
    expect(query).toHaveBeenCalledTimes(2); // notes is not an id field
    for (const [sql, params] of query.mock.calls) {
      expect(sql).toContain('tenant_id = $1');
      expect(params[0]).toBe(TENANT);
    }
  });

  it('labels item rows with booking number, date and service', async () => {
    const { repo, query } = build(() => [
      {
        id: 'item-1',
        booking_id: 'b-1',
        booking_number: 'MT-114473',
        item_date: '2026-11-13',
        item_label: 'DXB AIRPORT → DEIRA',
      },
    ]);
    const ctx = await repo.loadItemContext([row('booking_transport_item'), row('user')]);
    expect(ctx.get('item-1')).toEqual({
      booking_id: 'b-1',
      item_date: '2026-11-13',
      booking_number: 'MT-114473',
      item_label: 'DXB AIRPORT → DEIRA',
    });
    expect(query).toHaveBeenCalledTimes(1); // 'user' rows need no lookup
    expect(query.mock.calls[0][0]).toContain('t.tenant_id = $1');
  });
});
