import { ForbiddenException } from '@nestjs/common';
import { Prisma } from '@prisma/client';
import { submoduloHabilitado } from '../../auth/guards/submodulo.guard';
import { solicitudInvalida } from '../../common/utils/error-estructurado';
import { isContabilidadEnabledForEmpresa } from '../../common/utils/module-access.util';
import { ymdInAsuncion } from '../../utils/utilidades';
import { armar, cheque, CTA_PYG, CTA_USD, EMP, errorDe, ID, MOV, movimiento, USER } from './__helpers__/cheques-mock';
import { PERMITIDOS } from './reglas-cheque';

jest.mock('../../common/utils/module-access.util', () => ({ ...jest.requireActual('../../common/utils/module-access.util'), isContabilidadEnabledForEmpresa: jest.fn() }));
jest.mock('../../auth/guards/submodulo.guard', () => ({ ...jest.requireActual('../../auth/guards/submodulo.guard'), submoduloHabilitado: jest.fn() }));
jest.mock('../../utils/utilidades', () => ({ ...jest.requireActual('../../utils/utilidades'), ymdInAsuncion: jest.fn() }));
const conContabilidad = isContabilidadEnabledForEmpresa as jest.Mock;
const submodulo = submoduloHabilitado as jest.Mock;
const hoy = ymdInAsuncion as jest.Mock;

const dia = (d: string) => new Date(`${d}T00:00:00.000Z`);
const acreditar = (o: Record<string, unknown> = {}) => ({ cuenta_id: CTA_PYG, ...o }) as never;
const motivo = { motivo: 'El banco lo devolvió' } as never;

beforeEach(() => {
  conContabilidad.mockReset().mockResolvedValue(true);
  submodulo.mockReset().mockResolvedValue({ habilitado: true, fechaFinPrueba: null });
  hoy.mockReset().mockReturnValue('2026-11-03');
});

describe('TesChequeService: un id que no es UUID → 404 CHEQUE_NO_ENCONTRADO sin consultar Prisma', () => {
  const llamadas: Array<[string, (s: any) => Promise<unknown>]> = [
    ['depositar', (s) => s.depositar('abc', acreditar(), EMP, USER)],
    ['debitar', (s) => s.debitar('abc', acreditar(), EMP, USER)],
    ['rechazar', (s) => s.rechazar('abc', motivo, EMP, USER)],
    ['devolver', (s) => s.devolver('abc', motivo, EMP, USER)],
    ['anular', (s) => s.anular('abc', motivo, EMP, USER)],
    ['deshacerDeposito', (s) => s.deshacerDeposito('abc', EMP, USER)],
    ['update', (s) => s.update('abc', { motivo: 'x' }, EMP, USER)],
    ['remove', (s) => s.remove('abc', EMP, USER)],
    ['reintentarContabilizacion', (s) => s.reintentarContabilizacion(EMP, 'abc')],
  ];
  it.each(llamadas)('%s', async (_n, llamar) => {
    const { service, prisma } = armar();
    expect(await errorDe(llamar(service))).toMatchObject({ status: 404, codigo: 'CHEQUE_NO_ENCONTRADO' });
    expect(prisma.tes_cheques.findFirst).not.toHaveBeenCalled();
  });
});

describe('alta', () => {
  const dto = (o: Record<string, unknown> = {}) => ({ tipo: 'RECIBIDO', numero_cheque: '123', monto: 1000, fecha_emision: '2026-11-03', confirmar_duplicado: true, ...o }) as never;

  it.each([
    ['fecha_emision', { fecha_emision: '0006-01-08' }],
    ['fecha_vencimiento', { fecha_vencimiento: '0207-01-09' }],
    ['fecha_vencimiento', { fecha_vencimiento: '2037-01-01' }],
  ])('M1: %s con un año imposible → 400 FECHA_INVALIDA sin crear', async (campo, o) => {
    const { service, prisma } = armar();
    expect(await errorDe(service.create(dto(o), EMP, USER))).toMatchObject({ status: 400, codigo: 'FECHA_INVALIDA', campo });
    expect(prisma.tes_cheques.create).not.toHaveBeenCalled();
  });
  it('M1: el borde de la cota (2000 y hoy + 10) se acepta', async () => {
    const { service, prisma } = armar();
    await service.create(dto({ fecha_emision: '2000-01-01', fecha_vencimiento: '2036-12-31' }), EMP, USER);
    expect(prisma.tes_cheques.create).toHaveBeenCalled();
  });

  it('EMITIDO sin cuenta → 400 CAMPO_REQUERIDO cuenta_id', async () => {
    const { service, prisma } = armar();
    expect(await errorDe(service.create(dto({ tipo: 'EMITIDO' }), EMP, USER))).toMatchObject({ status: 400, codigo: 'CAMPO_REQUERIDO', campo: 'cuenta_id' });
    expect(prisma.tes_cheques.create).not.toHaveBeenCalled();
  });
  it('cuenta ajena o cerrada → 400 CUENTA_INVALIDA cuenta_id', async () => {
    const { service } = armar();
    expect(await errorDe(service.create(dto({ cuenta_id: '99999999-9999-4999-8999-999999999999' }), EMP, USER))).toMatchObject({
      status: 400,
      codigo: 'CUENTA_INVALIDA',
      campo: 'cuenta_id',
    });
  });
  it('B6: con la cuenta USD y sin moneda → moneda USD', async () => {
    const { service, prisma } = armar();
    await service.create(dto({ cuenta_id: CTA_USD }), EMP, USER);
    expect(prisma.tes_cheques.create.mock.calls[0][0].data.moneda).toBe('USD');
  });
  it('B6: con la cuenta USD y moneda PYG → 400 MONEDA_DISTINTA cuenta_id', async () => {
    const { service, prisma } = armar();
    expect(await errorDe(service.create(dto({ cuenta_id: CTA_USD, moneda: 'PYG' }), EMP, USER))).toMatchObject({ status: 400, codigo: 'MONEDA_DISTINTA', campo: 'cuenta_id' });
    expect(prisma.tes_cheques.create).not.toHaveBeenCalled();
  });
  it('RECIBIDO sin cuenta y sin moneda → PYG', async () => {
    const { service, prisma } = armar();
    await service.create(dto(), EMP, USER);
    expect(prisma.tes_cheques.create.mock.calls[0][0].data.moneda).toBe('PYG');
  });
  it('H6: vence mañana en Asunción → DIFERIDO; vence hoy → EN_CARTERA', async () => {
    const a = armar();
    await a.service.create(dto({ fecha_vencimiento: '2026-11-04' }), EMP, USER);
    expect(a.prisma.tes_cheques.create.mock.calls[0][0].data.estado).toBe('DIFERIDO');
    const b = armar();
    await b.service.create(dto({ fecha_vencimiento: '2026-11-03' }), EMP, USER);
    expect(b.prisma.tes_cheques.create.mock.calls[0][0].data.estado).toBe('EN_CARTERA');
  });
  it('EMITIDO toma el banco y el número de la cuenta', async () => {
    const { service, prisma } = armar();
    await service.create(dto({ tipo: 'EMITIDO', cuenta_id: CTA_PYG }), EMP, USER);
    expect(prisma.tes_cheques.create.mock.calls[0][0].data).toMatchObject({ banco_emisor: 'Banco Continental', cuenta_bancaria_origen: '123', cuenta_id: CTA_PYG, moneda: 'PYG' });
  });
  it('responde la fila (monto número) y deja la auditoría', async () => {
    const { service, audit } = armar();
    const r = await service.create(dto(), EMP, USER);
    expect(r).toMatchObject({ monto: 1000, movimientos: [], origen: null });
    expect(audit.log).toHaveBeenCalledWith(expect.objectContaining({ action: 'TES_CHEQUE_REGISTRADO' }));
  });
});

/** Las siete acciones con su guarda: lo que se lee, cómo se llama y la condición extra del `where`. */
const GUARDAS: Array<{ accion: keyof typeof PERMITIDOS; leido: Record<string, unknown>; llamar: (s: any) => Promise<unknown>; extra: Record<string, unknown> }> = [
  { accion: 'depositar', leido: {}, llamar: (s) => s.depositar(ID, acreditar(), EMP, USER), extra: { tipo: 'RECIBIDO' } },
  { accion: 'debitar', leido: { tipo: 'EMITIDO', cuenta_id: CTA_PYG }, llamar: (s) => s.debitar(ID, acreditar(), EMP, USER), extra: { tipo: 'EMITIDO' } },
  { accion: 'rechazar', leido: {}, llamar: (s) => s.rechazar(ID, motivo, EMP, USER), extra: {} },
  { accion: 'devolver', leido: {}, llamar: (s) => s.devolver(ID, motivo, EMP, USER), extra: { tipo: 'RECIBIDO', origen_tipo: null } },
  { accion: 'anular', leido: { tipo: 'EMITIDO' }, llamar: (s) => s.anular(ID, motivo, EMP, USER), extra: { tipo: 'EMITIDO' } },
  {
    accion: 'deshacer',
    leido: { estado: 'DEPOSITADO', movimiento_id: MOV, movimiento: movimiento() },
    llamar: (s) => s.deshacerDeposito(ID, EMP, USER),
    extra: { movimiento_id: MOV, movimiento: { estado: 'CONFIRMADO' } },
  },
  { accion: 'editar', leido: {}, llamar: (s) => s.update(ID, { titular: 'Otro', motivo: 'x' }, EMP, USER), extra: {} },
];

describe('guarda por estado en la transacción (B4)', () => {
  it.each(GUARDAS)('$accion: updateMany que cuenta 0 → 409 ESTADO_CAMBIADO sin movimiento ni saldo', async ({ accion, leido, llamar, extra }) => {
    const { service, tx } = armar({ cheque: cheque(leido), cuenta: 0 });
    expect(await errorDe(llamar(service))).toMatchObject({ status: 409, codigo: 'ESTADO_CAMBIADO' });
    const where = tx.tes_cheques.updateMany.mock.calls[0][0].where;
    expect(where).toMatchObject({ id: ID, empresa_id: EMP, ...extra });
    for (const e of where.estado.in) expect(PERMITIDOS[accion]).toContain(e);
    expect(tx.tes_movimientos.create).not.toHaveBeenCalled();
    expect(tx.tes_movimientos.updateMany).not.toHaveBeenCalled();
    expect(tx.tes_cuentas.update).not.toHaveBeenCalled();
  });

  it('eliminar: deleteMany con { id, empresa_id, estado in EN_CARTERA/DIFERIDO, origen_tipo: null } que cuenta 0 → 409', async () => {
    const { service, tx, audit } = armar({ cuenta: 0 });
    expect(await errorDe(service.remove(ID, EMP, USER))).toMatchObject({ status: 409, codigo: 'ESTADO_CAMBIADO' });
    expect(tx.tes_cheques.deleteMany).toHaveBeenCalledWith({ where: { id: ID, empresa_id: EMP, estado: { in: ['EN_CARTERA', 'DIFERIDO'] }, origen_tipo: null } });
    expect(audit.log).not.toHaveBeenCalled();
  });

  const fueraDeEstado: Array<[string, string, (s: any) => Promise<unknown>]> = [
    ['depositar', 'DEPOSITADO', (s) => s.depositar(ID, acreditar(), EMP, USER)],
    ['rechazar', 'RECHAZADO', (s) => s.rechazar(ID, motivo, EMP, USER)],
    ['devolver', 'DEVUELTO', (s) => s.devolver(ID, motivo, EMP, USER)],
    ['deshacer', 'EN_CARTERA', (s) => s.deshacerDeposito(ID, EMP, USER)],
    ['deshacer', 'RECHAZADO', (s) => s.deshacerDeposito(ID, EMP, USER)],
    ['editar', 'DEPOSITADO', (s) => s.update(ID, { titular: 'x', motivo: 'x' }, EMP, USER)],
    ['eliminar', 'DEPOSITADO', (s) => s.remove(ID, EMP, USER)],
  ];
  it.each(fueraDeEstado)('%s de un %s → 409 sin abrir la transacción', async (_a, estado, llamar) => {
    const { service, prisma } = armar({ cheque: cheque({ estado }) });
    expect(await errorDe(llamar(service))).toMatchObject({ status: 409, codigo: 'ESTADO_CAMBIADO' });
    expect(prisma.$transaction).not.toHaveBeenCalled();
  });
});

describe('depositar y debitar', () => {
  it('depositar un RECIBIDO EN_CARTERA de Gs. 2.500.000 en «DOBA S.A.»: todo en el tx', async () => {
    const { service, tx } = armar();
    await service.depositar(ID, acreditar({ fecha_movimiento: '2026-11-02' }), EMP, USER);
    expect(tx.tes_cheques.updateMany).toHaveBeenCalledWith(
      expect.objectContaining({
        where: expect.objectContaining({ id: ID, empresa_id: EMP, estado: { in: ['EN_CARTERA', 'DIFERIDO'] }, tipo: 'RECIBIDO' }),
        data: expect.objectContaining({ estado: 'DEPOSITADO', cuenta_id: CTA_PYG }),
      }),
    );
    const mov = tx.tes_movimientos.create.mock.calls[0][0].data;
    expect(mov).toMatchObject({ tipo: 'INGRESO', estado: 'CONFIRMADO', origen_tipo: 'CHEQUE_DEPOSITADO', origen_id: ID, cuenta_id: CTA_PYG, fecha: dia('2026-11-02') });
    expect(Number(mov.monto)).toBe(2500000);
    expect(tx.tes_cuentas.update).toHaveBeenCalledWith({ where: { id: CTA_PYG }, data: { saldo_actual: { increment: 2500000 } } });
    expect(tx.tes_cheques.update).toHaveBeenCalledWith({ where: { id: ID }, data: { movimiento_id: 'mov-nuevo' } });
  });

  it('el integrador se llama después del commit y esperado; la respuesta trae la fila y el asiento', async () => {
    const { service, prisma, contabilidad } = armar({ despues: cheque({ estado: 'DEPOSITADO', movimiento_id: 'mov-nuevo', cuenta_id: CTA_PYG }) });
    const r = await service.depositar(ID, acreditar(), EMP, USER);
    expect(contabilidad.integrarMovimientoTesoreria).toHaveBeenCalledWith('mov-nuevo');
    expect(prisma.$transaction.mock.invocationCallOrder[0]).toBeLessThan(contabilidad.integrarMovimientoTesoreria.mock.invocationCallOrder[0]);
    expect(r).toMatchObject({ estado: 'DEPOSITADO', monto: 2500000, asiento: { generado: true, motivo: null } });
  });

  it('el integrador lanza Error("boom") → la fila DEPOSITADO con asiento ERROR_INESPERADO sin mensaje; la tx se commiteó una vez', async () => {
    const { service, prisma, tx } = armar({ integrador: jest.fn().mockRejectedValue(new Error('boom')), despues: cheque({ estado: 'DEPOSITADO' }) });
    (service as any).logger = { log: jest.fn(), warn: jest.fn(), error: jest.fn() };
    const r = await service.depositar(ID, acreditar(), EMP, USER);
    expect(r.estado).toBe('DEPOSITADO');
    expect(r.asiento).toEqual({ generado: false, motivo: 'ERROR', codigo: 'ERROR_INESPERADO' });
    expect(prisma.$transaction).toHaveBeenCalledTimes(1);
    expect(tx.tes_cuentas.update).toHaveBeenCalledTimes(1);
  });

  it.each([
    [{ generado: true }, { generado: true, motivo: null }],
    [
      { generado: false, motivo: 'CATEGORIA_SIN_CUENTA', categoria: 'Cheque Depositado' },
      { generado: false, motivo: 'CATEGORIA_SIN_CUENTA', categoria: 'Cheque Depositado' },
    ],
    [
      { generado: false, motivo: 'SIN_MODULO' },
      { generado: false, motivo: 'SIN_MODULO' },
    ],
    [
      { generado: false, motivo: 'CUENTA_SIN_CUENTA_CONTABLE' },
      { generado: false, motivo: 'CUENTA_SIN_CUENTA_CONTABLE' },
    ],
    [
      { generado: false, motivo: 'SIN_PERIODO_ABIERTO' },
      { generado: false, motivo: 'SIN_PERIODO_ABIERTO' },
    ],
  ])('asiento: el integrador devuelve %j → %j', async (resultado, asiento) => {
    const { service } = armar({ integrador: jest.fn().mockResolvedValue(resultado) });
    expect((await service.depositar(ID, acreditar(), EMP, USER)).asiento).toEqual(asiento);
  });

  it('asiento: undefined con la constancia ACCION_FALTA_MAPEO de tes_movimientos → FALTA_MAPEO con sus conceptos', async () => {
    const { service, prisma } = armar({ integrador: jest.fn().mockResolvedValue(undefined), constancia: { new_value: { conceptos: ['CHEQUES_EN_CARTERA'] } } });
    const r = await service.depositar(ID, acreditar(), EMP, USER);
    expect(r.asiento).toEqual({ generado: false, motivo: 'FALTA_MAPEO', conceptos: ['CHEQUES_EN_CARTERA'] });
    expect(prisma.audit_logs.findFirst).toHaveBeenCalledWith(
      expect.objectContaining({ where: expect.objectContaining({ entity_type: 'tes_movimientos', entity_id: 'mov-nuevo' }) }),
    );
  });

  it('depositar un EMITIDO → 400 CHEQUE_TIPO_INVALIDO', async () => {
    const { service, prisma } = armar({ cheque: cheque({ tipo: 'EMITIDO' }) });
    expect(await errorDe(service.depositar(ID, acreditar(), EMP, USER))).toMatchObject({ status: 400, codigo: 'CHEQUE_TIPO_INVALIDO' });
    expect(prisma.$transaction).not.toHaveBeenCalled();
  });

  it('DIFERIDO que vence mañana → 400 CHEQUE_DIFERIDO con la fecha; que vence hoy → deposita', async () => {
    const a = armar({ cheque: cheque({ estado: 'DIFERIDO', fecha_vencimiento: dia('2026-11-04') }) });
    const e = await errorDe(a.service.depositar(ID, acreditar(), EMP, USER));
    expect(e).toMatchObject({ status: 400, codigo: 'CHEQUE_DIFERIDO' });
    expect(e!.message).toContain('04/11/2026');
    const b = armar({ cheque: cheque({ estado: 'DIFERIDO', fecha_vencimiento: dia('2026-11-03') }) });
    await b.service.depositar(ID, acreditar(), EMP, USER);
    expect(b.tx.tes_movimientos.create).toHaveBeenCalled();
  });

  it('fecha_movimiento futura → FECHA_FUTURA; anterior a la emisión → FECHA_ANTERIOR_EMISION (campo fecha_movimiento)', async () => {
    const { service } = armar();
    expect(await errorDe(service.depositar(ID, acreditar({ fecha_movimiento: '2026-11-04' }), EMP, USER))).toMatchObject({
      status: 400,
      codigo: 'FECHA_FUTURA',
      campo: 'fecha_movimiento',
    });
    expect(await errorDe(service.depositar(ID, acreditar({ fecha_movimiento: '2026-09-30' }), EMP, USER))).toMatchObject({
      status: 400,
      codigo: 'FECHA_ANTERIOR_EMISION',
      campo: 'fecha_movimiento',
    });
  });

  it('B6: depositar un PYG en una cuenta USD → 400 MONEDA_DISTINTA sin $transaction', async () => {
    const { service, prisma } = armar();
    expect(await errorDe(service.depositar(ID, acreditar({ cuenta_id: CTA_USD }), EMP, USER))).toMatchObject({ status: 400, codigo: 'MONEDA_DISTINTA', campo: 'cuenta_id' });
    expect(prisma.$transaction).not.toHaveBeenCalled();
  });

  it('cuenta cerrada o ajena → 400 CUENTA_INVALIDA', async () => {
    const { service } = armar();
    expect(await errorDe(service.depositar(ID, acreditar({ cuenta_id: '99999999-9999-4999-8999-999999999999' }), EMP, USER))).toMatchObject({
      status: 400,
      codigo: 'CUENTA_INVALIDA',
      campo: 'cuenta_id',
    });
  });

  it('debitar desde otra cuenta que la del cheque → 400 CHEQUE_OTRA_CUENTA', async () => {
    const { service, prisma } = armar({ cheque: cheque({ tipo: 'EMITIDO', cuenta_id: CTA_USD }) });
    expect(await errorDe(service.debitar(ID, acreditar(), EMP, USER))).toMatchObject({ status: 400, codigo: 'CHEQUE_OTRA_CUENTA', campo: 'cuenta_id' });
    expect(prisma.$transaction).not.toHaveBeenCalled();
  });

  it('debitar un EMITIDO sin cuenta (Kety) → debita y fija la cuenta; EGRESO que resta', async () => {
    const { service, tx } = armar({ cheque: cheque({ tipo: 'EMITIDO', cuenta_id: null }) });
    await service.debitar(ID, acreditar(), EMP, USER);
    expect(tx.tes_cheques.updateMany.mock.calls[0][0].data).toMatchObject({ estado: 'DEBITADO', cuenta_id: CTA_PYG });
    expect(tx.tes_movimientos.create.mock.calls[0][0].data).toMatchObject({ tipo: 'EGRESO', origen_tipo: 'CHEQUE_DEBITADO', origen_id: ID });
    expect(tx.tes_cuentas.update).toHaveBeenCalledWith({ where: { id: CTA_PYG }, data: { saldo_actual: { increment: -2500000 } } });
  });

  it('debitar un RECIBIDO → 400 CHEQUE_TIPO_INVALIDO', async () => {
    const { service } = armar();
    expect(await errorDe(service.debitar(ID, acreditar(), EMP, USER))).toMatchObject({ status: 400, codigo: 'CHEQUE_TIPO_INVALIDO' });
  });

  describe('B8: el origen ya movió el saldo', () => {
    it.each([
      ['debitar', 'EMITIDO', 'RENDICION_ADELANTO'],
      ['depositar', 'RECIBIDO', 'RENDICION_DEVOLUCION'],
      ['debitar', 'EMITIDO', 'CXP_EMPLEADO_PAGO'],
    ])('%s un %s EN_CARTERA de %s con movimiento_id CONFIRMADO → 400 CHEQUE_SALDO_EN_ORIGEN sin $transaction', async (accion, tipo, origen) => {
      const { service, prisma } = armar({ cheque: cheque({ tipo, origen_tipo: origen, origen_id: 'o-1', movimiento_id: MOV, movimiento: movimiento({ origen_tipo: origen }) }) });
      const e = await errorDe((service as any)[accion](ID, acreditar(), EMP, USER));
      expect(e).toMatchObject({ status: 400, codigo: 'CHEQUE_SALDO_EN_ORIGEN' });
      expect(e!.message).toContain('RRHH → Rendición de viáticos');
      expect(prisma.$transaction).not.toHaveBeenCalled();
    });
    it.each(['RENDICION_ADELANTO', 'RENDICION_DEVOLUCION', 'CXP_EMPLEADO_PAGO'])(
      'M6: de %s sin movimiento vigente (debitado con el bug viejo y deshecho) → 400 CHEQUE_SALDO_EN_ORIGEN',
      async (origen) => {
        const { service, prisma } = armar({ cheque: cheque({ tipo: 'EMITIDO', origen_tipo: origen, origen_id: 'o-1', movimiento_id: null, movimiento: null }) });
        expect(await errorDe(service.debitar(ID, acreditar(), EMP, USER))).toMatchObject({ status: 400, codigo: 'CHEQUE_SALDO_EN_ORIGEN' });
        expect(await errorDe(service.anular(ID, { motivo: 'x' } as never, EMP, USER))).toMatchObject({ status: 400, codigo: 'CHEQUE_SALDO_EN_ORIGEN' });
        expect(prisma.$transaction).not.toHaveBeenCalled();
      },
    );
    it('M2 y T1 M2: la guarda repite el monto leído, la operabilidad y B8 en la transacción', async () => {
      const leido = cheque();
      const { service, tx } = armar({ cheque: leido });
      await service.depositar(ID, acreditar(), EMP, USER);
      expect(tx.tes_cheques.updateMany.mock.calls[0][0].where).toMatchObject({
        monto: leido.monto,
        AND: [
          { OR: [{ estado: 'EN_CARTERA' }, { fecha_vencimiento: null }, { fecha_vencimiento: { lte: dia('2026-11-03') } }] },
          { OR: [{ movimiento_id: null }, { movimiento: { estado: { not: 'CONFIRMADO' } } }] },
          { OR: [{ origen_tipo: null }, { origen_tipo: { notIn: ['RENDICION_ADELANTO', 'RENDICION_DEVOLUCION', 'CXP_EMPLEADO_PAGO'] } }] },
        ],
      });
    });
    it('M2: una edición del monto en el medio cuenta 0 → 409 sin movimiento ni saldo', async () => {
      const { service, tx } = armar({ cuenta: 0 });
      expect(await errorDe(service.depositar(ID, acreditar(), EMP, USER))).toMatchObject({ status: 409, codigo: 'ESTADO_CAMBIADO' });
      expect(tx.tes_movimientos.create).not.toHaveBeenCalled();
      expect(tx.tes_cuentas.update).not.toHaveBeenCalled();
    });
    it('con movimiento_id ANULADO (los 56 de DOBA) → deposita', async () => {
      const { service, tx } = armar({
        cheque: cheque({ origen_tipo: 'recibos_multi', origen_id: 'rec-1', movimiento_id: MOV, movimiento: movimiento({ estado: 'ANULADO', origen_tipo: 'recibos_multi' }) }),
      });
      await service.depositar(ID, acreditar(), EMP, USER);
      expect(tx.tes_movimientos.create).toHaveBeenCalled();
    });
  });
});

describe('rechazar, anular y devolver', () => {
  it('rechazar un DIFERIDO → RECHAZADO con el motivo, sin movimiento y asiento null (B2)', async () => {
    const { service, tx, contabilidad } = armar({ cheque: cheque({ estado: 'DIFERIDO', fecha_vencimiento: dia('2026-12-01') }) });
    const r = await service.rechazar(ID, motivo, EMP, USER);
    expect(tx.tes_cheques.updateMany.mock.calls[0][0]).toMatchObject({
      where: { estado: { in: ['EN_CARTERA', 'DIFERIDO'] } },
      data: { estado: 'RECHAZADO', motivo: 'El banco lo devolvió' },
    });
    expect(tx.tes_movimientos.create).not.toHaveBeenCalled();
    expect(contabilidad.integrarMovimientoTesoreria).not.toHaveBeenCalled();
    expect(r.asiento).toBeNull();
  });

  it('anular un EMITIDO DIFERIDO → ANULADO, asiento null (B2)', async () => {
    const { service, tx } = armar({ cheque: cheque({ tipo: 'EMITIDO', estado: 'DIFERIDO' }) });
    const r = await service.anular(ID, motivo, EMP, USER);
    expect(tx.tes_cheques.updateMany.mock.calls[0][0].data).toMatchObject({ estado: 'ANULADO' });
    expect(r.asiento).toBeNull();
  });

  it('rechazar un DEPOSITADO de 4.200.000: EGRESO CHEQUE_RECHAZADO en la cuenta del movimiento, con fecha de hoy; después el asiento', async () => {
    const mov = movimiento({ monto: new Prisma.Decimal(4200000) });
    const { service, tx, prisma, contabilidad } = armar({ cheque: cheque({ estado: 'DEPOSITADO', cuenta_id: CTA_PYG, movimiento_id: MOV, movimiento: mov }) });
    const r = await service.rechazar(ID, motivo, EMP, USER);
    expect(tx.tes_cheques.updateMany.mock.calls[0][0].where).toEqual({
      id: ID,
      empresa_id: EMP,
      estado: { in: ['DEPOSITADO'] },
      movimiento_id: MOV,
      movimiento: { estado: 'CONFIRMADO' },
    });
    expect(tx.tes_movimientos.create.mock.calls[0][0].data).toMatchObject({
      tipo: 'EGRESO',
      origen_tipo: 'CHEQUE_RECHAZADO',
      origen_id: ID,
      cuenta_id: CTA_PYG,
      fecha: dia('2026-11-03'),
    });
    expect(tx.tes_cuentas.update).toHaveBeenCalledWith({ where: { id: CTA_PYG }, data: { saldo_actual: { increment: -4200000 } } });
    expect(contabilidad.integrarMovimientoTesoreria).toHaveBeenCalledWith('mov-nuevo');
    expect(prisma.$transaction.mock.invocationCallOrder[0]).toBeLessThan(contabilidad.integrarMovimientoTesoreria.mock.invocationCallOrder[0]);
    expect(r.asiento).toEqual({ generado: true, motivo: null });
  });

  it('F3: rechazar con la cuenta del movimiento cerrada procede', async () => {
    const { service, tx } = armar({ cheque: cheque({ estado: 'DEPOSITADO', movimiento_id: MOV, movimiento: movimiento({ cuenta: { nombre: 'X', activo: false } }) }) });
    await service.rechazar(ID, motivo, EMP, USER);
    expect(tx.tes_movimientos.create).toHaveBeenCalled();
  });

  it('anular un DEBITADO: INGRESO CHEQUE_ANULADO que devuelve el saldo, con su asiento', async () => {
    const mov = movimiento({ tipo: 'EGRESO', origen_tipo: 'CHEQUE_DEBITADO', monto: new Prisma.Decimal(1000000) });
    const { service, tx } = armar({ cheque: cheque({ tipo: 'EMITIDO', estado: 'DEBITADO', movimiento_id: MOV, movimiento: mov }) });
    const r = await service.anular(ID, motivo, EMP, USER);
    expect(tx.tes_movimientos.create.mock.calls[0][0].data).toMatchObject({ tipo: 'INGRESO', origen_tipo: 'CHEQUE_ANULADO', origen_id: ID });
    expect(tx.tes_cuentas.update).toHaveBeenCalledWith({ where: { id: CTA_PYG }, data: { saldo_actual: { increment: 1000000 } } });
    expect(r.asiento).toEqual({ generado: true, motivo: null });
  });

  it('anular un RECIBIDO → 400 CHEQUE_TIPO_INVALIDO; devolver un EMITIDO igual', async () => {
    const a = armar();
    expect(await errorDe(a.service.anular(ID, motivo, EMP, USER))).toMatchObject({ status: 400, codigo: 'CHEQUE_TIPO_INVALIDO' });
    const b = armar({ cheque: cheque({ tipo: 'EMITIDO' }) });
    expect(await errorDe(b.service.devolver(ID, motivo, EMP, USER))).toMatchObject({ status: 400, codigo: 'CHEQUE_TIPO_INVALIDO' });
  });

  it('B3: devolver un recibido de un recibo → 400 CHEQUE_CON_ORIGEN que nombra el documento y dónde se corrige; sin updateMany', async () => {
    const { service, tx } = armar({ cheque: cheque({ origen_tipo: 'recibos_multi', origen_id: 'rec-1' }) });
    const e = await errorDe(service.devolver(ID, motivo, EMP, USER));
    expect(e).toMatchObject({ status: 400, codigo: 'CHEQUE_CON_ORIGEN' });
    expect(e!.message).toContain('Recibo de cobro');
    expect(e!.message).toContain('Cobranzas → Recibos');
    expect(tx.tes_cheques.updateMany).not.toHaveBeenCalled();
  });

  it('devolver un manual EN_CARTERA → DEVUELTO con asiento null', async () => {
    const { service, tx } = armar();
    const r = await service.devolver(ID, motivo, EMP, USER);
    expect(tx.tes_cheques.updateMany.mock.calls[0][0].data).toMatchObject({ estado: 'DEVUELTO', motivo: 'El banco lo devolvió' });
    expect(r.asiento).toBeNull();
  });

  it('rechazar un cheque de recibo EN_CARTERA → RECHAZADO (sin bloqueo)', async () => {
    const { service, tx } = armar({ cheque: cheque({ origen_tipo: 'recibos_multi', origen_id: 'rec-1' }) });
    await service.rechazar(ID, motivo, EMP, USER);
    expect(tx.tes_cheques.updateMany).toHaveBeenCalled();
  });

  it('B8: rechazar un RECIBIDO EN_CARTERA de RENDICION_DEVOLUCION con movimiento CONFIRMADO → 400; anular un EMITIDO de RENDICION_ADELANTO igual', async () => {
    const a = armar({
      cheque: cheque({ origen_tipo: 'RENDICION_DEVOLUCION', origen_id: 'd-1', movimiento_id: MOV, movimiento: movimiento({ origen_tipo: 'RENDICION_DEVOLUCION' }) }),
    });
    expect(await errorDe(a.service.rechazar(ID, motivo, EMP, USER))).toMatchObject({ status: 400, codigo: 'CHEQUE_SALDO_EN_ORIGEN' });
    expect(a.prisma.$transaction).not.toHaveBeenCalled();
    const b = armar({
      cheque: cheque({ tipo: 'EMITIDO', origen_tipo: 'RENDICION_ADELANTO', origen_id: 'a-1', movimiento_id: MOV, movimiento: movimiento({ origen_tipo: 'RENDICION_ADELANTO' }) }),
    });
    expect(await errorDe(b.service.anular(ID, motivo, EMP, USER))).toMatchObject({ status: 400, codigo: 'CHEQUE_SALDO_EN_ORIGEN' });
  });

  it('F2: rechazar un DEPOSITADO cuyo movimiento está ANULADO → 400 CHEQUE_SIN_MOVIMIENTO antes de la tx', async () => {
    const { service, prisma } = armar({ cheque: cheque({ estado: 'DEPOSITADO', movimiento_id: MOV, movimiento: movimiento({ estado: 'ANULADO' }) }) });
    const e = await errorDe(service.rechazar(ID, motivo, EMP, USER));
    expect(e).toMatchObject({ status: 400, codigo: 'CHEQUE_SIN_MOVIMIENTO' });
    expect(e!.message).toContain('su movimiento está anulado: consultá al contador');
    expect(prisma.$transaction).not.toHaveBeenCalled();
  });

  it('F2: anular un DEBITADO sin movimiento vigente (Kety nº 25864498) igual', async () => {
    const { service, prisma } = armar({
      cheque: cheque({ tipo: 'EMITIDO', estado: 'DEBITADO', movimiento_id: MOV, movimiento: movimiento({ estado: 'ANULADO', tipo: 'EGRESO' }) }),
    });
    expect(await errorDe(service.anular(ID, motivo, EMP, USER))).toMatchObject({ status: 400, codigo: 'CHEQUE_SIN_MOVIMIENTO' });
    expect(prisma.$transaction).not.toHaveBeenCalled();
  });

  it('F2: si entre la lectura y la tx cambió el movimiento_id, el updateMany cuenta 0 → 409 sin reversa', async () => {
    const { service, tx, contabilidad } = armar({ cheque: cheque({ estado: 'DEPOSITADO', movimiento_id: MOV, movimiento: movimiento() }), cuenta: 0 });
    expect(await errorDe(service.rechazar(ID, motivo, EMP, USER))).toMatchObject({ status: 409, codigo: 'ESTADO_CAMBIADO' });
    expect(tx.tes_movimientos.create).not.toHaveBeenCalled();
    expect(contabilidad.integrarMovimientoTesoreria).not.toHaveBeenCalled();
  });
});

describe('deshacer depósito o débito', () => {
  const depositado = (o: Record<string, unknown> = {}) =>
    cheque({ estado: 'DEPOSITADO', cuenta_id: CTA_PYG, movimiento_id: MOV, movimiento: movimiento({ monto: new Prisma.Decimal(4040709) }), ...o });

  it('anula el movimiento (sin reversa), devuelve el saldo, vuelve a EN_CARTERA y suelta movimiento_id y acreditado_en', async () => {
    const { service, tx } = armar({ cheque: depositado() });
    await service.deshacerDeposito(ID, EMP, USER);
    expect(tx.tes_movimientos.create).not.toHaveBeenCalled();
    const m = tx.tes_movimientos.updateMany.mock.calls[0][0];
    expect(m.where).toEqual({ id: MOV, empresa_id: EMP, estado: 'CONFIRMADO', extracto_lineas: { none: { conciliado: true } } });
    // F10: guarda quién y cuándo, sin inventar un motivo.
    expect(m.data).toMatchObject({ estado: 'ANULADO', anulado_por: USER, anulado_en: expect.any(Date) });
    expect(m.data).not.toHaveProperty('motivo_anulacion');
    expect(tx.tes_cuentas.update).toHaveBeenCalledWith({ where: { id: CTA_PYG }, data: { saldo_actual: { increment: -4040709 } } });
    const c = tx.tes_cheques.updateMany.mock.calls[0][0];
    expect(c.where).toEqual({ id: ID, empresa_id: EMP, estado: { in: ['DEPOSITADO', 'DEBITADO'] }, movimiento_id: MOV, movimiento: { estado: 'CONFIRMADO' } });
    expect(c.data).toMatchObject({ estado: 'EN_CARTERA', movimiento_id: null, acreditado_en: null });
  });

  it('con vencimiento futuro vuelve a DIFERIDO', async () => {
    const { service, tx } = armar({ cheque: depositado({ fecha_vencimiento: dia('2026-12-01') }) });
    await service.deshacerDeposito(ID, EMP, USER);
    expect(tx.tes_cheques.updateMany.mock.calls[0][0].data.estado).toBe('DIFERIDO');
  });

  it('también el débito: el saldo vuelve', async () => {
    const { service, tx } = armar({
      cheque: cheque({
        tipo: 'EMITIDO',
        estado: 'DEBITADO',
        movimiento_id: MOV,
        movimiento: movimiento({ tipo: 'EGRESO', origen_tipo: 'CHEQUE_DEBITADO', monto: new Prisma.Decimal(1000000) }),
      }),
    });
    await service.deshacerDeposito(ID, EMP, USER);
    expect(tx.tes_cuentas.update).toHaveBeenCalledWith({ where: { id: CTA_PYG }, data: { saldo_actual: { increment: 1000000 } } });
  });

  it('conciliado → 400 MOVIMIENTO_CONCILIADO sin abrir la tx', async () => {
    const { service, prisma } = armar({ cheque: depositado(), conciliado: true });
    expect(await errorDe(service.deshacerDeposito(ID, EMP, USER))).toMatchObject({ status: 400, codigo: 'MOVIMIENTO_CONCILIADO' });
    expect(prisma.$transaction).not.toHaveBeenCalled();
  });

  it('con CONTABILIDAD revierte el asiento dentro de la transacción', async () => {
    const { service, tx, contabilidad } = armar({ cheque: depositado() });
    await service.deshacerDeposito(ID, EMP, USER);
    expect(contabilidad.revertirDocumento).toHaveBeenCalledWith('tes_movimientos', MOV, USER, tx);
  });

  it('con CONTABILIDAD y el período cerrado → 400 ASIENTO_NO_REVERTIDO con el mensaje de asientos y el $transaction propaga', async () => {
    const texto = 'No se puede revertir: el período 05/2026 del asiento está CERRADO. Reabrilo o pedile al contador.';
    const revertir = jest.fn().mockRejectedValue(solicitudInvalida({ codigo: 'PERIODO_NO_ABIERTO', message: texto }));
    const { service, audit } = armar({ cheque: depositado(), revertir });
    expect(await errorDe(service.deshacerDeposito(ID, EMP, USER))).toMatchObject({ status: 400, codigo: 'ASIENTO_NO_REVERTIDO', message: texto });
    expect(audit.log).not.toHaveBeenCalled();
  });

  it('sin CONTABILIDAD, con el mismo error mockeado → deshace y no llama a revertirDocumento', async () => {
    conContabilidad.mockResolvedValue(false);
    const revertir = jest.fn().mockRejectedValue(solicitudInvalida({ codigo: 'PERIODO_NO_ABIERTO', message: 'x' }));
    const { service, tx } = armar({ cheque: depositado(), revertir });
    await service.deshacerDeposito(ID, EMP, USER);
    expect(revertir).not.toHaveBeenCalled();
    expect(tx.tes_cuentas.update).toHaveBeenCalled();
  });

  it('otro error de revertirDocumento sale tal cual', async () => {
    const { service } = armar({ cheque: depositado(), revertir: jest.fn().mockRejectedValue(new Error('se cayó')) });
    await expect(service.deshacerDeposito(ID, EMP, USER)).rejects.toThrow('se cayó');
  });

  it('el updateMany del movimiento cuenta 0 → 409 sin tocar el saldo', async () => {
    const { service, tx } = armar({ cheque: depositado(), cuentaMovimiento: 0 });
    expect(await errorDe(service.deshacerDeposito(ID, EMP, USER))).toMatchObject({ status: 409, codigo: 'ESTADO_CAMBIADO' });
    expect(tx.tes_cuentas.update).not.toHaveBeenCalled();
  });

  it('F10: conciliado entre el chequeo y la tx → 400 MOVIMIENTO_CONCILIADO sin tocar el saldo', async () => {
    const { service, tx } = armar({ cheque: depositado(), cuentaMovimiento: 0, conciliadoEnTx: true });
    expect(await errorDe(service.deshacerDeposito(ID, EMP, USER))).toMatchObject({ status: 400, codigo: 'MOVIMIENTO_CONCILIADO' });
    expect(tx.tes_cuentas.update).not.toHaveBeenCalled();
  });

  it('F2: DEPOSITADO con su movimiento ANULADO → 400 CHEQUE_SIN_MOVIMIENTO (no 409) sin abrir la tx', async () => {
    const { service, prisma } = armar({ cheque: depositado({ movimiento: movimiento({ estado: 'ANULADO' }) }) });
    expect(await errorDe(service.deshacerDeposito(ID, EMP, USER))).toMatchObject({ status: 400, codigo: 'CHEQUE_SIN_MOVIMIENTO' });
    expect(prisma.$transaction).not.toHaveBeenCalled();
  });

  it('F3: DEBITADO con el movimiento en una cuenta cerrada → 400 CUENTA_INVALIDA que nombra la cuenta, sin abrir la tx', async () => {
    const { service, prisma } = armar({
      cheque: cheque({
        tipo: 'EMITIDO',
        estado: 'DEBITADO',
        movimiento_id: MOV,
        movimiento: movimiento({ tipo: 'EGRESO', cuenta: { nombre: 'FAMILIAR COMERCIAL KETY', activo: false } }),
      }),
    });
    const e = await errorDe(service.deshacerDeposito(ID, EMP, USER));
    expect(e).toMatchObject({ status: 400, codigo: 'CUENTA_INVALIDA' });
    expect(e!.message).toContain('Reactivá la cuenta FAMILIAR COMERCIAL KETY en Configuración › Cuentas');
    expect(prisma.$transaction).not.toHaveBeenCalled();
  });

  it('F4: a las 23:30 de Asunción del 2026-11-03 (02:30 UTC del 04) vuelve a DIFERIDO el que vence el 04 y a EN_CARTERA el que vence el 03', async () => {
    hoy.mockImplementation(jest.requireActual('../../utils/utilidades').ymdInAsuncion);
    jest.useFakeTimers().setSystemTime(new Date('2026-11-04T02:30:00.000Z'));
    try {
      const a = armar({ cheque: depositado({ fecha_vencimiento: dia('2026-11-04') }) });
      await a.service.deshacerDeposito(ID, EMP, USER);
      expect(a.tx.tes_cheques.updateMany.mock.calls[0][0].data.estado).toBe('DIFERIDO');
      const b = armar({ cheque: depositado({ fecha_vencimiento: dia('2026-11-03') }) });
      await b.service.deshacerDeposito(ID, EMP, USER);
      expect(b.tx.tes_cheques.updateMany.mock.calls[0][0].data.estado).toBe('EN_CARTERA');
    } finally {
      jest.useRealTimers();
    }
  });
});

describe('editar', () => {
  it('sin cambios → 400 SIN_CAMBIOS', async () => {
    const { service } = armar();
    expect(await errorDe(service.update(ID, { titular: 'Juan Pérez', motivo: 'x' } as never, EMP, USER))).toMatchObject({ status: 400, codigo: 'SIN_CAMBIOS' });
  });
  it('M1: cambiar a un año imposible → 400 FECHA_INVALIDA sin escribir', async () => {
    const { service, tx } = armar();
    expect(await errorDe(service.update(ID, { fecha_vencimiento: '0207-01-09', motivo: 'x' } as never, EMP, USER))).toMatchObject({
      status: 400,
      codigo: 'FECHA_INVALIDA',
      campo: 'fecha_vencimiento',
    });
    expect(tx.tes_cheques.updateMany).not.toHaveBeenCalled();
  });
  it('M1: un cheque con una fecha imposible vieja se edita en lo demás y se corrige', async () => {
    const vieja = cheque({ fecha_emision: dia('0006-01-08') });
    const a = armar({ cheque: vieja });
    await a.service.update(ID, { fecha_emision: '0006-01-08', titular: 'Otro', motivo: 'x' } as never, EMP, USER);
    expect(a.tx.tes_cheques.updateMany.mock.calls[0][0].data).toMatchObject({ titular: 'Otro' });
    const b = armar({ cheque: vieja });
    await b.service.update(ID, { fecha_emision: '2026-01-08', motivo: 'x' } as never, EMP, USER);
    expect(b.tx.tes_cheques.updateMany.mock.calls[0][0].data.fecha_emision).toEqual(dia('2026-01-08'));
  });
  it('numero_cheque vacío o null → CAMPO_REQUERIDO numero_cheque; fecha_emision null → campo fecha_emision', async () => {
    const { service } = armar();
    expect(await errorDe(service.update(ID, { numero_cheque: '', motivo: 'x' } as never, EMP, USER))).toMatchObject({
      status: 400,
      codigo: 'CAMPO_REQUERIDO',
      campo: 'numero_cheque',
    });
    expect(await errorDe(service.update(ID, { numero_cheque: null, motivo: 'x' } as never, EMP, USER))).toMatchObject({ codigo: 'CAMPO_REQUERIDO', campo: 'numero_cheque' });
    expect(await errorDe(service.update(ID, { fecha_emision: null, motivo: 'x' } as never, EMP, USER))).toMatchObject({ codigo: 'CAMPO_REQUERIDO', campo: 'fecha_emision' });
  });
  it('D11: EN_CARTERA a vencer el 10/11 → DIFERIDO; DIFERIDO a vencer hoy → EN_CARTERA; DIFERIDO sin vencimiento → EN_CARTERA', async () => {
    const a = armar();
    await a.service.update(ID, { fecha_vencimiento: '2026-11-10', motivo: 'x' } as never, EMP, USER);
    expect(a.tx.tes_cheques.updateMany.mock.calls[0][0].data).toMatchObject({ estado: 'DIFERIDO', fecha_vencimiento: dia('2026-11-10') });
    const b = armar({ cheque: cheque({ estado: 'DIFERIDO', fecha_vencimiento: dia('2026-11-20') }) });
    await b.service.update(ID, { fecha_vencimiento: '2026-11-03', motivo: 'x' } as never, EMP, USER);
    expect(b.tx.tes_cheques.updateMany.mock.calls[0][0].data.estado).toBe('EN_CARTERA');
    const c = armar({ cheque: cheque({ estado: 'DIFERIDO', fecha_vencimiento: dia('2026-11-20') }) });
    await c.service.update(ID, { fecha_vencimiento: null, motivo: 'x' } as never, EMP, USER);
    expect(c.tx.tes_cheques.updateMany.mock.calls[0][0].data).toMatchObject({ estado: 'EN_CARTERA', fecha_vencimiento: null });
  });
  it('F9: el EN_CARTERA nº 1611567 (vence 2027-01-30) editado solo en referencia no cambia de estado; con el mismo vencimiento tampoco; con otro sí', async () => {
    const leido = cheque({ numero_cheque: '1611567', estado: 'EN_CARTERA', fecha_vencimiento: dia('2027-01-30') });
    const a = armar({ cheque: leido });
    await a.service.update(ID, { referencia: 'nota', motivo: 'x' } as never, EMP, USER);
    expect(a.tx.tes_cheques.updateMany.mock.calls[0][0].data).not.toHaveProperty('estado');
    const b = armar({ cheque: leido });
    await b.service.update(ID, { referencia: 'nota', fecha_vencimiento: '2027-01-30', motivo: 'x' } as never, EMP, USER);
    expect(b.tx.tes_cheques.updateMany.mock.calls[0][0].data).not.toHaveProperty('estado');
    const c = armar({ cheque: leido });
    await c.service.update(ID, { fecha_vencimiento: '2027-02-10', motivo: 'x' } as never, EMP, USER);
    expect(c.tx.tes_cheques.updateMany.mock.calls[0][0].data.estado).toBe('DIFERIDO');
  });
  it('el where lleva estado in EN_CARTERA/DIFERIDO y responde la fila', async () => {
    const { service, tx, audit } = armar({ despues: cheque({ titular: 'Otro' }) });
    const r = await service.update(ID, { titular: 'Otro', motivo: 'corrección' } as never, EMP, USER);
    expect(tx.tes_cheques.updateMany.mock.calls[0][0].where).toEqual({ id: ID, empresa_id: EMP, estado: { in: ['EN_CARTERA', 'DIFERIDO'] } });
    expect(r).toMatchObject({ titular: 'Otro', monto: 2500000 });
    expect(audit.log).toHaveBeenCalledWith(expect.objectContaining({ action: 'TES_CHEQUE_EDITADO' }));
  });
  it('el monto de un cheque de una OP no se edita: MONTO_NO_EDITABLE que nombra la orden de pago', async () => {
    const { service } = armar({ cheque: cheque({ tipo: 'EMITIDO', origen_tipo: 'ORDEN_PAGO_PROVEEDOR', origen_id: 'op-1' }) });
    const e = await errorDe(service.update(ID, { monto: 1, motivo: 'x' } as never, EMP, USER));
    expect(e).toMatchObject({ status: 400, codigo: 'MONTO_NO_EDITABLE', campo: 'monto' });
    expect(e!.message).toContain('Orden de pago a proveedor');
  });
});

describe('eliminar', () => {
  it('un DIFERIDO manual → deleteMany que cuenta 1 → { id } y la auditoría después', async () => {
    const { service, tx, audit } = armar({ cheque: cheque({ estado: 'DIFERIDO' }) });
    expect(await service.remove(ID, EMP, USER)).toEqual({ id: ID });
    expect(tx.tes_cheques.deleteMany).toHaveBeenCalledWith({ where: { id: ID, empresa_id: EMP, estado: { in: ['EN_CARTERA', 'DIFERIDO'] }, origen_tipo: null } });
    expect(audit.log).toHaveBeenCalledWith(expect.objectContaining({ action: 'TES_CHEQUE_ELIMINADO', entity_id: ID }));
    expect(tx.tes_cheques.deleteMany.mock.invocationCallOrder[0]).toBeLessThan(audit.log.mock.invocationCallOrder[0]);
  });
  it('B3: con origen → 400 CHEQUE_CON_ORIGEN sin deleteMany', async () => {
    const { service, tx } = armar({ cheque: cheque({ tipo: 'EMITIDO', estado: 'DIFERIDO', origen_tipo: 'ORDEN_PAGO_PROVEEDOR', origen_id: 'op-1' }) });
    const e = await errorDe(service.remove(ID, EMP, USER));
    expect(e).toMatchObject({ status: 400, codigo: 'CHEQUE_CON_ORIGEN' });
    expect(e!.message).toContain('Compras → Órdenes de pago');
    expect(tx.tes_cheques.deleteMany).not.toHaveBeenCalled();
  });
});

describe('reintentar contabilización', () => {
  const movsConfirmados = (ids: string[]) => ids.map((id) => ({ id }));

  it('sin el submódulo CONTABILIDAD_CONCILIACION → 403 sin llamar al integrador', async () => {
    submodulo.mockResolvedValue({ habilitado: false, causa: 'fuera_del_plan', mensaje: 'Conciliación contable no está en el plan' });
    const { service, contabilidad } = armar();
    await expect(service.reintentarContabilizacion(EMP, ID)).rejects.toBeInstanceOf(ForbiddenException);
    expect(contabilidad.integrarMovimientoTesoreria).not.toHaveBeenCalled();
  });
  it('cheque inexistente → 404', async () => {
    const { service } = armar({ cheque: null });
    expect(await errorDe(service.reintentarContabilizacion(EMP, ID))).toMatchObject({ status: 404, codigo: 'CHEQUE_NO_ENCONTRADO' });
  });
  it('sin movimientos CHEQUE_* CONFIRMADOS → 400 CHEQUE_SIN_MOVIMIENTO', async () => {
    const { service } = armar({ movimientos: [] });
    expect(await errorDe(service.reintentarContabilizacion(EMP, ID))).toMatchObject({ status: 400, codigo: 'CHEQUE_SIN_MOVIMIENTO' });
  });
  it('DEPOSITADO sin documento: contabiliza el movimiento y responde contabilizada', async () => {
    const { service, prisma, contabilidad } = armar({ cheque: cheque({ estado: 'DEPOSITADO' }), movimientos: movsConfirmados(['m-dep']) });
    prisma.cont_documentos.findMany.mockResolvedValueOnce([]).mockResolvedValueOnce([{ origen_id: 'm-dep' }]);
    const r = await service.reintentarContabilizacion(EMP, ID);
    expect(prisma.tes_movimientos.findMany).toHaveBeenCalledWith(
      expect.objectContaining({
        where: { empresa_id: EMP, origen_id: ID, origen_tipo: { in: ['CHEQUE_DEPOSITADO', 'CHEQUE_DEBITADO', 'CHEQUE_RECHAZADO', 'CHEQUE_ANULADO'] }, estado: 'CONFIRMADO' },
      }),
    );
    expect(contabilidad.integrarMovimientoTesoreria).toHaveBeenCalledWith('m-dep');
    expect(r).toEqual({ contabilizada: true, asiento: { generado: true, motivo: null } });
  });
  it('con FALTA_MAPEO → contabilizada false con los conceptos', async () => {
    const { service, prisma } = armar({
      cheque: cheque({ estado: 'DEPOSITADO' }),
      movimientos: movsConfirmados(['m-dep']),
      integrador: jest.fn().mockResolvedValue(undefined),
      constancia: { new_value: { conceptos: ['CHEQUES_EN_CARTERA'] } },
    });
    prisma.cont_documentos.findMany.mockResolvedValue([]);
    expect(await service.reintentarContabilizacion(EMP, ID)).toEqual({
      contabilizada: false,
      asiento: { generado: false, motivo: 'FALTA_MAPEO', conceptos: ['CHEQUES_EN_CARTERA'] },
    });
  });
  it('RECHAZADO con el depósito contabilizado y la reversa sin documento → solo contabiliza la reversa', async () => {
    const { service, prisma, contabilidad } = armar({ cheque: cheque({ estado: 'RECHAZADO' }), movimientos: movsConfirmados(['m-dep', 'm-rev']) });
    prisma.cont_documentos.findMany.mockResolvedValueOnce([{ origen_id: 'm-dep' }]).mockResolvedValueOnce([{ origen_id: 'm-dep' }, { origen_id: 'm-rev' }]);
    const r = await service.reintentarContabilizacion(EMP, ID);
    expect(contabilidad.integrarMovimientoTesoreria).toHaveBeenCalledTimes(1);
    expect(contabilidad.integrarMovimientoTesoreria).toHaveBeenCalledWith('m-rev');
    expect(r.contabilizada).toBe(true);
  });
});

describe('cron de diferidos y fechas (F4)', () => {
  it('a las 23:30 de Asunción del 2026-11-03, pasa a EN_CARTERA los que vencen hasta el 03 (no el 04), con la guarda DIFERIDO', async () => {
    hoy.mockImplementation(jest.requireActual('../../utils/utilidades').ymdInAsuncion);
    jest.useFakeTimers().setSystemTime(new Date('2026-11-04T02:30:00.000Z'));
    try {
      const { service, prisma } = armar();
      prisma.tes_cheques.findMany.mockResolvedValue([{ id: ID, empresa_id: EMP, numero_cheque: '1', monto: 1, moneda: 'PYG', fecha_vencimiento: dia('2026-11-03') }]);
      prisma.tes_cheques.updateManyAndReturn = jest.fn().mockResolvedValue([{ id: ID }]);
      await service.transicionarDiferidosAlDia();
      expect(prisma.tes_cheques.findMany.mock.calls[0][0].where).toEqual({ estado: 'DIFERIDO', fecha_vencimiento: { lte: dia('2026-11-03') } });
      expect(prisma.tes_cheques.updateManyAndReturn.mock.calls[0][0].where).toEqual({ id: { in: [ID] }, estado: 'DIFERIDO', fecha_vencimiento: { lte: dia('2026-11-03') } });
    } finally {
      jest.useRealTimers();
    }
  });
  it('T1 M1: la auditoría cuenta los que cambiaron: uno editado a futuro en el medio no figura', async () => {
    const { service, prisma, audit } = armar();
    const fila = (id: string) => ({ id, empresa_id: EMP, numero_cheque: id, monto: 1, moneda: 'PYG', fecha_vencimiento: dia('2026-11-03') });
    prisma.tes_cheques.findMany.mockResolvedValue([fila('a'), fila('b')]);
    prisma.tes_cheques.updateManyAndReturn = jest.fn().mockResolvedValue([{ id: 'a' }]);
    await service.transicionarDiferidosAlDia();
    expect(audit.log).toHaveBeenCalledTimes(1);
    const nuevo = audit.log.mock.calls[0][0].new_value;
    expect(nuevo.cantidad).toBe(1);
    expect(nuevo.cheques.map((c: { id: string }) => c.id)).toEqual(['a']);
  });
  it('T1 M1: si ninguno cambió, no se audita', async () => {
    const { service, prisma, audit } = armar();
    prisma.tes_cheques.findMany.mockResolvedValue([{ id: 'a', empresa_id: EMP, numero_cheque: 'a', monto: 1, moneda: 'PYG', fecha_vencimiento: dia('2026-11-03') }]);
    prisma.tes_cheques.updateManyAndReturn = jest.fn().mockResolvedValue([]);
    await service.transicionarDiferidosAlDia();
    expect(audit.log).not.toHaveBeenCalled();
  });
  it('onModuleInit corre lo mismo', async () => {
    const { service, prisma } = armar();
    await service.onModuleInit();
    expect(prisma.tes_cheques.findMany.mock.calls[0][0].where).toEqual({ estado: 'DIFERIDO', fecha_vencimiento: { lte: dia('2026-11-03') } });
  });
  it('la reversa de rechazar y el depósito sin fecha_movimiento guardan el día de Asunción (23:30 del 03 → 2026-11-03)', async () => {
    hoy.mockImplementation(jest.requireActual('../../utils/utilidades').ymdInAsuncion);
    jest.useFakeTimers().setSystemTime(new Date('2026-11-04T02:30:00.000Z'));
    try {
      const a = armar();
      await a.service.depositar(ID, acreditar(), EMP, USER);
      expect(a.tx.tes_movimientos.create.mock.calls[0][0].data.fecha).toEqual(dia('2026-11-03'));
      const b = armar({ cheque: cheque({ estado: 'DEPOSITADO', movimiento_id: MOV, movimiento: movimiento() }) });
      await b.service.rechazar(ID, motivo, EMP, USER);
      expect(b.tx.tes_movimientos.create.mock.calls[0][0].data.fecha).toEqual(dia('2026-11-03'));
    } finally {
      jest.useRealTimers();
    }
  });
});
