import { AuditService } from './audit.service';

/**
 * `getByEntity` (historial de una entidad) tiene que quedar acotado a las empresas que el usuario puede ver, con el
 * mismo criterio que `getPaginated`: los ids de entidad se repiten entre empresas (o se adivinan) y sin el filtro se
 * leía el historial de otra empresa.
 */
describe('AuditService.getByEntity', () => {
  const crear = (logs: Array<{ id: string; empresa_id: string }> = []) => {
    const prisma: any = {
      audit_logs: {
        // Simula a Postgres: aplica el filtro de empresa que reciba (sin filtro, devuelve todo).
        findMany: jest.fn(({ where }: any) =>
          Promise.resolve(logs.filter((l) => !where.empresa_id || (where.empresa_id.in as string[]).includes(l.empresa_id))),
        ),
      },
      empresas: { findMany: jest.fn().mockResolvedValue([{ id: 'emp-hija' }]) },
    };
    return { service: new AuditService(prisma), prisma };
  };

  const LOGS = [
    { id: 'log-propio', empresa_id: 'emp-1' },
    { id: 'log-ajeno', empresa_id: 'emp-otra' },
    { id: 'log-hija', empresa_id: 'emp-hija' },
  ];

  it('empresa normal: solo su empresa, un log de otra empresa con el mismo entity_id no sale', async () => {
    const { service, prisma } = crear(LOGS);
    const r = await service.getByEntity('emp-1', null, 'factura', 'f-1');
    expect(r.map((l: any) => l.id)).toEqual(['log-propio']);
    const where = prisma.audit_logs.findMany.mock.calls[0][0].where;
    expect(where).toEqual({ entity_type: 'factura', entity_id: 'f-1', empresa_id: { in: ['emp-1'] } });
    // Una subsidiaria no busca hijas.
    expect(prisma.empresas.findMany).not.toHaveBeenCalled();
  });

  it('holding: la propia y sus subsidiarias activas, nunca una ajena', async () => {
    const { service, prisma } = crear(LOGS);
    const r = await service.getByEntity('emp-1', 'holding', 'factura', 'f-1');
    expect(r.map((l: any) => l.id).sort()).toEqual(['log-hija', 'log-propio']);
    expect(prisma.empresas.findMany.mock.calls[0][0].where).toEqual({ parent_id: 'emp-1', active: true });
  });

  it('reseller: mismo criterio que holding', async () => {
    const { service } = crear(LOGS);
    const r = await service.getByEntity('emp-1', 'reseller', 'factura', 'f-1');
    expect(r.map((l: any) => l.id).sort()).toEqual(['log-hija', 'log-propio']);
  });

  it.each([
    [undefined, 50],
    [10, 10],
    [5000, 200],
    [0, 1],
    [-3, 1],
    [NaN, 50],
  ])('limit %p se acota a %p', async (limit, take) => {
    const { service, prisma } = crear();
    await service.getByEntity('emp-1', null, 'factura', 'f-1', limit);
    expect(prisma.audit_logs.findMany.mock.calls[0][0].take).toBe(take);
  });

  it('ordena del más nuevo al más viejo', async () => {
    const { service, prisma } = crear();
    await service.getByEntity('emp-1', null, 'factura', 'f-1');
    expect(prisma.audit_logs.findMany.mock.calls[0][0].orderBy).toEqual({ created_at: 'desc' });
  });
});
