import { ValidationPipe } from '@nestjs/common';
import { UpdateTesConfigDto } from './dto/tes-config.dto';
import { TesConfigService } from './services/tes-config.service';

function armar(monedasActivas: string[] = ['PYG', 'USD'], fila: any = null) {
  const prisma: any = {
    tes_config: {
      findUnique: jest.fn().mockResolvedValue(fila),
      upsert: jest.fn().mockImplementation(({ create }) => Promise.resolve({ id: 'c1', ...create })),
    },
    empresa_monedas: {
      findFirst: jest
        .fn()
        .mockImplementation(({ where }) =>
          where.active === true && where.empresa_id === 'emp' && monedasActivas.includes(where.moneda.codigo) ? { id: 'em' } : null,
        ),
    },
  };
  return { service: new TesConfigService(prisma), prisma };
}

describe('TesConfigService', () => {
  it('sin fila: get → null', async () => {
    const { service } = armar();
    await expect(service.get('emp')).resolves.toBeNull();
  });

  it('guardar hace upsert por empresa_id con solo los campos del dto y updated_at', async () => {
    const { service, prisma } = armar();
    await service.guardar('emp', { dias_alerta_cheques: 10 });
    const arg = prisma.tes_config.upsert.mock.calls[0][0];
    expect(arg.where).toEqual({ empresa_id: 'emp' });
    expect(arg.create).toEqual({ empresa_id: 'emp', dias_alerta_cheques: 10 });
    expect(Object.keys(arg.update).sort()).toEqual(['dias_alerta_cheques', 'updated_at']);
    expect(arg.update.updated_at).toBeInstanceOf(Date);
  });

  it('el umbral 0 se guarda (no se confunde con ausente)', async () => {
    const { service, prisma } = armar();
    await service.guardar('emp', { monto_umbral_aprobacion: 0 });
    expect(prisma.tes_config.upsert.mock.calls[0][0].update.monto_umbral_aprobacion).toBe(0);
  });

  it('moneda base que la empresa no tiene activa → MONEDA_NO_HABILITADA con campo moneda_base_reportes, sin escribir', async () => {
    const { service, prisma } = armar(['PYG']);
    await expect(service.guardar('emp', { moneda_base_reportes: 'USD' })).rejects.toMatchObject({
      response: { codigo: 'MONEDA_NO_HABILITADA', campo: 'moneda_base_reportes' },
    });
    expect(prisma.tes_config.upsert).not.toHaveBeenCalled();
  });

  it('moneda base activa → guarda', async () => {
    const { service, prisma } = armar(['PYG', 'USD']);
    await service.guardar('emp', { moneda_base_reportes: 'USD' });
    expect(prisma.tes_config.upsert.mock.calls[0][0].create.moneda_base_reportes).toBe('USD');
  });
});

describe('UpdateTesConfigDto (ValidationPipe global)', () => {
  const pipe = new ValidationPipe({ whitelist: true, forbidNonWhitelisted: true, transform: true });
  const validar = (body: unknown) => pipe.transform(body, { type: 'body', metatype: UpdateTesConfigDto });

  it('{ empresa_id } → 400', async () => {
    await expect(validar({ empresa_id: 'otra' })).rejects.toMatchObject({ status: 400 });
  });
  it.each([0, 91, 7.5])('dias_alerta_cheques %p → 400', async (n) => {
    await expect(validar({ dias_alerta_cheques: n })).rejects.toMatchObject({ status: 400 });
  });
  it.each([1, 90])('dias_alerta_cheques %p pasa', async (n) => {
    await expect(validar({ dias_alerta_cheques: n })).resolves.toMatchObject({ dias_alerta_cheques: n });
  });
  it('monto_umbral_aprobacion -1 → 400; 0 pasa', async () => {
    await expect(validar({ monto_umbral_aprobacion: -1 })).rejects.toMatchObject({ status: 400 });
    await expect(validar({ monto_umbral_aprobacion: 0 })).resolves.toMatchObject({ monto_umbral_aprobacion: 0 });
  });
  it('monto con más de 2 decimales → 400', async () => {
    await expect(validar({ monto_umbral_aprobacion: 1.234 })).rejects.toMatchObject({ status: 400 });
  });
  it.each(['monto_umbral_aprobacion', 'dias_alerta_cheques', 'moneda_base_reportes'])('{ %s: null } → 400 (las columnas son NOT NULL)', async (campo) => {
    await expect(validar({ [campo]: null })).rejects.toMatchObject({ status: 400 });
  });
  it('{} pasa: todo es opcional', async () => {
    await expect(validar({})).resolves.toBeDefined();
  });
  it("moneda_base_reportes 'PY' → 400", async () => {
    await expect(validar({ moneda_base_reportes: 'PY' })).rejects.toMatchObject({ status: 400 });
  });
});
