import { HttpException } from '@nestjs/common';
import { AuditController } from './audit.controller';

/** El cable que cierra `/audit/entity` a la empresa: empresa del token + tipo leído de la BD. */
describe('AuditController.getEntityHistory', () => {
  const crear = (type: string | null = 'holding') => {
    const auditService: any = { getByEntity: jest.fn().mockResolvedValue([{ id: 'log-1' }]) };
    const prisma: any = { empresas: { findUnique: jest.fn().mockResolvedValue({ type }) } };
    return { controller: new AuditController(auditService, prisma), auditService, prisma };
  };

  it('pasa la empresa del usuario y su tipo leído de la BD', async () => {
    const { controller, auditService, prisma } = crear('holding');
    const r = await controller.getEntityHistory({ empresa_id: 'emp-1' } as any, 'factura', 'f-1', '20');
    expect(r).toEqual([{ id: 'log-1' }]);
    expect(prisma.empresas.findUnique).toHaveBeenCalledWith({ where: { id: 'emp-1' }, select: { type: true } });
    expect(auditService.getByEntity).toHaveBeenCalledWith('emp-1', 'holding', 'factura', 'f-1', 20);
  });

  it('sin empresa en el token → 400 y no consulta nada', async () => {
    const { controller, auditService } = crear();
    const llamada = controller.getEntityHistory({ empresa_id: undefined } as any, 'factura', 'f-1');
    await expect(llamada).rejects.toBeInstanceOf(HttpException);
    await expect(controller.getEntityHistory({} as any, 'factura', 'f-1')).rejects.toMatchObject({ status: 400 });
    expect(auditService.getByEntity).not.toHaveBeenCalled();
  });
});
