import { PrismaClient } from '@prisma/client';
import { filtroUsuarioHabilitado } from './estado-usuario';

/**
 * Contra la base local, dentro de una transacción que se revierte: el `where` real de Prisma incluye al usuario Activo con
 * `active` NULL y deja afuera al desactivado y al de otro estado.
 */
describe('filtroUsuarioHabilitado contra la base (transacción revertida)', () => {
  const prisma = new PrismaClient();
  afterAll(() => prisma.$disconnect());

  it('Activo con active NULL o true entran; active false, Inactivo y Bloqueado no', async () => {
    const REVERTIR = new Error('revertir');
    let encontrados: string[] = [];
    await prisma
      .$transaction(async (tx) => {
        const empresa = await tx.empresas.findFirstOrThrow({ select: { id: true } });
        const crear = (username: string, estado: string, active: boolean | null) =>
          tx.usuario.create({ data: { empresa_id: empresa.id, username, estado, active }, select: { id: true } });
        const [nulo, activo, apagado, inactivo, bloqueado] = await Promise.all([
          crear('t1b-nulo', 'Activo', null),
          crear('t1b-activo', 'Activo', true),
          crear('t1b-apagado', 'Activo', false),
          crear('t1b-inactivo', 'Inactivo', true),
          crear('t1b-bloqueado', 'Bloqueado', null),
        ]);
        const ids = [nulo, activo, apagado, inactivo, bloqueado].map((u) => u.id);
        const filas = await tx.usuario.findMany({ where: { id: { in: ids }, ...filtroUsuarioHabilitado }, select: { username: true } });
        encontrados = filas.map((f) => f.username as string).sort();
        throw REVERTIR;
      })
      .catch((e) => {
        if (e !== REVERTIR) throw e;
      });
    expect(encontrados).toEqual(['t1b-activo', 't1b-nulo']);
    expect(await prisma.usuario.count({ where: { username: { startsWith: 't1b-' } } })).toBe(0);
  });
});
