import { Prisma } from '@prisma/client';
import { submoduloHabilitado } from '../../auth/guards/submodulo.guard';
import { solicitudInvalida } from '../../common/utils/error-estructurado';
import { armar, CAT, CTA, EMP, errorDe, EXT, LIN, linea, MOV, movimiento, USER } from './__helpers__/conciliacion-mock';

jest.mock('../../common/utils/module-access.util', () => ({
  ...jest.requireActual('../../common/utils/module-access.util'),
  isContabilidadEnabledForEmpresa: jest.fn().mockResolvedValue(true),
}));
jest.mock('../../auth/guards/submodulo.guard', () => ({ submoduloHabilitado: jest.fn() }));
jest.mock('../../utils/utilidades', () => ({ ...jest.requireActual('../../utils/utilidades'), ymdInAsuncion: jest.fn(() => '2026-11-04') }));

const submodulo = submoduloHabilitado as jest.Mock;
const dec = (n: number) => new Prisma.Decimal(n);

describe('guarda y bloqueo, en cada escritura de una línea (D4)', () => {
  const acciones: Array<[string, (s: ReturnType<typeof armar>['service']) => Promise<unknown>, Record<string, unknown>]> = [
    ['conciliar', (s) => s.conciliarLinea(EMP, LIN, MOV), { conciliado: false, sin_correspondencia: false }],
    ['desconciliar', (s) => s.desconciliarLinea(EMP, LIN), { conciliado: true }],
    ['marcar', (s) => s.marcarSinCorrespondencia(EMP, LIN), { conciliado: false, sin_correspondencia: false }],
    ['desmarcar', (s) => s.desmarcarSinCorrespondencia(EMP, LIN), { sin_correspondencia: true }],
    ['crear movimiento', (s) => s.crearMovimientoDesdeLinea(EMP, LIN, { categoria_id: CAT }, USER), { conciliado: false, sin_correspondencia: false, movimiento_id: null }],
    ['editar', (s) => s.actualizarLinea(EMP, LIN, { descripcion: 'x' }), { conciliado: false }],
  ];

  it.each(acciones)('%s: el where lleva la condición de la tabla', async (_n, accion, condicion) => {
    const { service, tx } = armar();
    await accion(service);
    expect(tx.tes_extracto_lineas.updateMany.mock.calls[0][0].where).toMatchObject({ id: LIN, ...condicion });
  });

  it.each(acciones)('%s: updateMany cuenta 0 → 409 ESTADO_CAMBIADO; no toca movimientos, saldo ni estado', async (_n, accion) => {
    const { service, tx } = armar({ guarda: 0 });
    expect(await errorDe(accion(service))).toMatchObject({ status: 409, codigo: 'ESTADO_CAMBIADO' });
    expect(tx.tes_movimientos.create).not.toHaveBeenCalled();
    expect(tx.tes_movimiento_det.create).not.toHaveBeenCalled();
    expect(tx.tes_cuentas.update).not.toHaveBeenCalled();
    expect(tx.tes_extracto_bancario.update).not.toHaveBeenCalled();
  });

  it.each(acciones)('%s: bloqueo del extracto, después la guarda, al final el estado; todo con el tx', async (_n, accion) => {
    const { service, orden, prisma, tx } = armar();
    await accion(service);
    const bloqueo = orden.indexOf('bloqueo-extracto');
    const guarda = orden.indexOf('lineas.updateMany');
    const estado = orden.indexOf('extracto.update');
    expect(bloqueo).toBeGreaterThan(-1);
    expect(bloqueo).toBeLessThan(guarda);
    expect(guarda).toBeLessThan(estado);
    expect(prisma.$transaction).toHaveBeenCalledTimes(1);
    expect(prisma.tes_extracto_bancario.update).not.toHaveBeenCalled();
    expect(tx.tes_extracto_bancario.update).toHaveBeenCalledTimes(1);
    expect(tx.$queryRaw.mock.calls[0][0].join('?')).toMatch(/SELECT id FROM tes_extracto_bancario WHERE id = \?::uuid FOR UPDATE/);
    expect(tx.$queryRaw.mock.calls[0][1]).toBe(EXT);
  });

  it.each(acciones)('%s: un id que no es UUID → 404 LINEA_NO_ENCONTRADA sin transacción', async (_n, accion) => {
    const { service, prisma } = armar();
    const conId = (id: string) => {
      const s = new Proxy(service, {
        get: (t, k) =>
          typeof (t as never)[k] === 'function'
            ? (emp: string, _l: string, ...r: unknown[]) => ((t as never)[k] as (...a: unknown[]) => unknown).call(t, emp, id, ...r)
            : (t as never)[k],
      });
      return accion(s);
    };
    expect(await errorDe(conId('abc'))).toMatchObject({ status: 404, codigo: 'LINEA_NO_ENCONTRADA' });
    expect(prisma.$transaction).not.toHaveBeenCalled();
  });

  it.each(acciones)('%s: línea ajena → 404 LINEA_NO_ENCONTRADA', async (_n, accion) => {
    expect(await errorDe(accion(armar({ linea: null }).service))).toMatchObject({ status: 404, codigo: 'LINEA_NO_ENCONTRADA' });
  });

  it('el extracto ya no está (lo eliminaron entre medio) → 409 y la guarda no corre', async () => {
    const { service, tx } = armar({ bloqueo: [] });
    expect(await errorDe(service.marcarSinCorrespondencia(EMP, LIN))).toMatchObject({ status: 409, codigo: 'ESTADO_CAMBIADO' });
    expect(tx.tes_extracto_lineas.updateMany).not.toHaveBeenCalled();
  });
});

describe('conciliarLinea', () => {
  const debito = (n: number) => linea({ debito: dec(n), credito: dec(0) });
  const credito = (n: number) => linea({ debito: dec(0), credito: dec(n) });
  const transferencia = (origen: string, monto = 3_700_000) => movimiento({ tipo: 'TRANSFERENCIA', origen_tipo: origen, monto: dec(monto) });

  it('relee el movimiento en el tx con FOR UPDATE, tras el extracto; débito 150.000 con EGRESO 150.000 → ok', async () => {
    const { service, tx, orden } = armar({ linea: debito(150_000), movimiento: movimiento({ monto: dec(150_000) }) });
    await expect(service.conciliarLinea(EMP, LIN, MOV)).resolves.toEqual({ ok: true });
    expect(orden.indexOf('bloqueo-extracto')).toBeLessThan(orden.indexOf('bloqueo-movimiento'));
    expect(orden.indexOf('bloqueo-movimiento')).toBeLessThan(orden.indexOf('movimiento.findFirst'));
    expect(orden.indexOf('movimiento.findFirst')).toBeLessThan(orden.indexOf('lineas.otra'));
    expect(orden.indexOf('lineas.otra')).toBeLessThan(orden.indexOf('lineas.updateMany'));
    expect(tx.$queryRaw.mock.calls[1][0].join('?')).toMatch(/SELECT id FROM tes_movimientos WHERE id = \?::uuid FOR UPDATE/);
    expect(tx.tes_movimientos.findFirst.mock.calls[0][0].where).toEqual({ id: MOV, empresa_id: EMP, estado: 'CONFIRMADO' });
    expect(tx.tes_extracto_lineas.updateMany.mock.calls[0][0].data).toEqual({ conciliado: true, movimiento_id: MOV, sin_correspondencia: false });
  });
  it('D7: una TRANSFERENCIA_ORIGEN de 3.700.000 con una línea de débito concilia', async () => {
    await expect(armar({ linea: debito(3_700_000), movimiento: transferencia('TRANSFERENCIA_ORIGEN') }).service.conciliarLinea(EMP, LIN, MOV)).resolves.toEqual({ ok: true });
  });
  it('D7: la misma con una línea de crédito → MOVIMIENTO_SENTIDO_DISTINTO', async () => {
    expect(await errorDe(armar({ linea: credito(3_700_000), movimiento: transferencia('TRANSFERENCIA_ORIGEN') }).service.conciliarLinea(EMP, LIN, MOV))).toMatchObject({
      status: 400,
      codigo: 'MOVIMIENTO_SENTIDO_DISTINTO',
      campo: 'movimiento_id',
    });
  });
  it('D7: una TRANSFERENCIA_DESTINO con crédito concilia', async () => {
    await expect(armar({ linea: credito(3_700_000), movimiento: transferencia('TRANSFERENCIA_DESTINO') }).service.conciliarLinea(EMP, LIN, MOV)).resolves.toEqual({ ok: true });
  });
  it('otra cuenta → MOVIMIENTO_OTRA_CUENTA', async () => {
    expect(await errorDe(armar({ movimiento: movimiento({ cuenta_id: 'otra' }) }).service.conciliarLinea(EMP, LIN, MOV))).toMatchObject({
      status: 400,
      codigo: 'MOVIMIENTO_OTRA_CUENTA',
      campo: 'movimiento_id',
    });
  });
  it('en PYG, la tolerancia del emparejado automático: a 1 Gs concilia, a 2 Gs → MOVIMIENTO_MONTO_DISTINTO', async () => {
    expect(await errorDe(armar({ movimiento: movimiento({ monto: dec(1002) }) }).service.conciliarLinea(EMP, LIN, MOV))).toMatchObject({
      status: 400,
      codigo: 'MOVIMIENTO_MONTO_DISTINTO',
      campo: 'movimiento_id',
    });
    await expect(armar({ movimiento: movimiento({ monto: dec(1001) }) }).service.conciliarLinea(EMP, LIN, MOV)).resolves.toEqual({ ok: true });
  });
  describe('en USD, ±0,01 comparado en centavos', () => {
    const lineaUsd = (monto: number) => linea({ debito: dec(monto), extracto: { cuenta_id: CTA, cuenta: { moneda: 'USD', activo: true } } });
    it('0,31 contra 0,30 concilia (en coma flotante la diferencia da más de 0,01)', async () => {
      await expect(armar({ linea: lineaUsd(0.3), movimiento: movimiento({ monto: dec(0.31) }) }).service.conciliarLinea(EMP, LIN, MOV)).resolves.toEqual({ ok: true });
    });
    it('a 0,02 → MOVIMIENTO_MONTO_DISTINTO', async () => {
      expect(await errorDe(armar({ linea: lineaUsd(100), movimiento: movimiento({ monto: dec(100.02) }) }).service.conciliarLinea(EMP, LIN, MOV))).toMatchObject({
        codigo: 'MOVIMIENTO_MONTO_DISTINTO',
      });
    });
    it('a 1 dólar no pasa: la tolerancia de 1 es solo de PYG', async () => {
      expect(await errorDe(armar({ linea: lineaUsd(100), movimiento: movimiento({ monto: dec(101) }) }).service.conciliarLinea(EMP, LIN, MOV))).toMatchObject({
        codigo: 'MOVIMIENTO_MONTO_DISTINTO',
      });
    });
  });
  it('en otra línea conciliada → MOVIMIENTO_YA_CONCILIADO y la guarda no corre', async () => {
    const { service, tx } = armar({ otraLinea: { id: 'otra' } });
    expect(await errorDe(service.conciliarLinea(EMP, LIN, MOV))).toMatchObject({ status: 400, codigo: 'MOVIMIENTO_YA_CONCILIADO', campo: 'movimiento_id' });
    expect(tx.tes_extracto_lineas.updateMany).not.toHaveBeenCalled();
  });
  it('ANULADO o ajeno → 404 MOVIMIENTO_NO_ENCONTRADO', async () => {
    expect(await errorDe(armar({ movimiento: null }).service.conciliarLinea(EMP, LIN, MOV))).toMatchObject({ status: 404, codigo: 'MOVIMIENTO_NO_ENCONTRADO' });
  });
  it('un movimiento_id que no es UUID → 404 MOVIMIENTO_NO_ENCONTRADO sin transacción', async () => {
    const { service, prisma } = armar();
    expect(await errorDe(service.conciliarLinea(EMP, LIN, 'abc'))).toMatchObject({ status: 404, codigo: 'MOVIMIENTO_NO_ENCONTRADO' });
    expect(prisma.$transaction).not.toHaveBeenCalled();
  });
  it('línea en 0 → LINEA_SIN_MONTO', async () => {
    const { service, prisma } = armar({ linea: debito(0) });
    expect(await errorDe(service.conciliarLinea(EMP, LIN, MOV))).toMatchObject({ status: 400, codigo: 'LINEA_SIN_MONTO' });
    expect(prisma.$transaction).not.toHaveBeenCalled();
  });
  it('la guarda exige el importe leído: una edición simultánea da 409, no un vínculo con otro monto', async () => {
    const { service, tx } = armar();
    await service.conciliarLinea(EMP, LIN, MOV);
    expect(tx.tes_extracto_lineas.updateMany.mock.calls[0][0].where).toMatchObject({ debito: dec(1000), credito: dec(0) });
  });
});

describe('desconciliarLinea', () => {
  it('deja conciliado false, movimiento_id null y no toca tes_movimientos ni tes_cuentas', async () => {
    const { service, tx } = armar({ linea: linea({ conciliado: true, movimiento_id: MOV }) });
    await expect(service.desconciliarLinea(EMP, LIN)).resolves.toEqual({ ok: true });
    expect(tx.tes_extracto_lineas.updateMany.mock.calls[0][0].data).toEqual({ conciliado: false, movimiento_id: null });
    expect(tx.tes_movimientos.create).not.toHaveBeenCalled();
    expect(tx.tes_movimientos.findFirst).not.toHaveBeenCalled();
    expect(tx.tes_cuentas.update).not.toHaveBeenCalled();
  });
});

describe('marcar y desmarcar sin correspondencia', () => {
  it('marcar pone true; desmarcar, false', async () => {
    const a = armar();
    await expect(a.service.marcarSinCorrespondencia(EMP, LIN)).resolves.toEqual({ ok: true });
    expect(a.tx.tes_extracto_lineas.updateMany.mock.calls[0][0].data).toEqual({ sin_correspondencia: true });
    const b = armar();
    await expect(b.service.desmarcarSinCorrespondencia(EMP, LIN)).resolves.toEqual({ ok: true });
    expect(b.tx.tes_extracto_lineas.updateMany.mock.calls[0][0].data).toEqual({ sin_correspondencia: false });
  });
});

describe('crearMovimientoDesdeLinea', () => {
  const crear = (e: Parameters<typeof armar>[0] = {}, data: { categoria_id: string; descripcion?: string } = { categoria_id: CAT }) => {
    const a = armar(e);
    return { ...a, promesa: a.service.crearMovimientoDesdeLinea(EMP, LIN, data, USER) };
  };

  it('débito 1.000 en una cuenta activa: guarda, EGRESO con su origen y referencia, detalle, saldo y vínculo, en ese orden', async () => {
    const { promesa, tx, orden } = crear();
    const r = await promesa;
    expect(r).toMatchObject({ ok: true, movimiento_id: MOV });
    const data = tx.tes_movimientos.create.mock.calls[0][0].data;
    expect(data).toMatchObject({
      empresa_id: EMP,
      cuenta_id: CTA,
      tipo: 'EGRESO',
      monto: 1000,
      estado: 'CONFIRMADO',
      origen_tipo: 'CONCILIACION_AJUSTE',
      origen_id: null,
      referencia: 'R-1',
      created_by: USER,
      confirmado_por: USER,
    });
    expect(data.confirmado_en).toBeInstanceOf(Date);
    expect(tx.tes_movimiento_det.create.mock.calls[0][0].data).toMatchObject({ movimiento_id: MOV, categoria_id: CAT, monto: 1000 });
    expect(tx.tes_cuentas.update).toHaveBeenCalledWith({ where: { id: CTA }, data: { saldo_actual: { decrement: 1000 } } });
    expect(tx.tes_extracto_lineas.update).toHaveBeenCalledWith({ where: { id: LIN }, data: { movimiento_id: MOV } });
    expect(tx.tes_extracto_lineas.updateMany.mock.calls[0][0].data).toEqual({ conciliado: true });
    const pos = ['lineas.updateMany', 'movimiento.create', 'det.create', 'cuenta.update', 'lineas.update', 'extracto.update'].map((n) => orden.indexOf(n));
    expect(pos.every((p) => p >= 0)).toBe(true);
    expect([...pos].sort((a, b) => a - b)).toEqual(pos);
  });
  it('crédito → INGRESO con increment', async () => {
    const { promesa, tx } = crear({ linea: linea({ debito: dec(0), credito: dec(500) }) });
    await promesa;
    expect(tx.tes_movimientos.create.mock.calls[0][0].data).toMatchObject({ tipo: 'INGRESO', monto: 500 });
    expect(tx.tes_cuentas.update).toHaveBeenCalledWith({ where: { id: CTA }, data: { saldo_actual: { increment: 500 } } });
  });
  it('la descripción: la del dato, si no la de la línea, si no la clave fija de hoy', async () => {
    const a = crear({}, { categoria_id: CAT, descripcion: 'Mía' });
    await a.promesa;
    expect(a.tx.tes_movimientos.create.mock.calls[0][0].data.descripcion).toBe('Mía');
    const b = crear({}, { categoria_id: CAT, descripcion: '' });
    await b.promesa;
    expect(b.tx.tes_movimientos.create.mock.calls[0][0].data.descripcion).toBe('COMISION BANCO');
    const c = crear({ linea: linea({ descripcion: null }) });
    await c.promesa;
    expect(c.tx.tes_movimientos.create.mock.calls[0][0].data.descripcion).toBe('Movimiento desde conciliación');
  });
  it('una descripción de 400: 400 en el movimiento, 300 en el detalle (F14)', async () => {
    const { promesa, tx } = crear({}, { categoria_id: CAT, descripcion: 'x'.repeat(400) });
    await promesa;
    expect(tx.tes_movimientos.create.mock.calls[0][0].data.descripcion).toHaveLength(400);
    expect(tx.tes_movimiento_det.create.mock.calls[0][0].data.descripcion).toHaveLength(300);
  });
  it.each([
    ['ajena', [{ id: CAT, tipo: 'AMBOS', activo: true, empresa_id: 'otra', is_sistema: false }]],
    ['inactiva', [{ id: CAT, tipo: 'AMBOS', activo: false, empresa_id: EMP, is_sistema: false }]],
    ['de otro tipo', [{ id: CAT, tipo: 'INGRESO', activo: true, empresa_id: EMP, is_sistema: false }]],
    ['inexistente', []],
  ])('categoría %s → 400 CATEGORIA_INVALIDA con campo categoria_id (F21), sin crear nada', async (_n, categorias) => {
    const { promesa, tx } = crear({ categorias });
    expect(await errorDe(promesa)).toMatchObject({ status: 400, codigo: 'CATEGORIA_INVALIDA', campo: 'categoria_id' });
    expect(tx.tes_movimientos.create).not.toHaveBeenCalled();
    expect(tx.tes_cuentas.update).not.toHaveBeenCalled();
  });
  it('cuenta cerrada → 400 CUENTA_INVALIDA sin crear nada', async () => {
    const { promesa, tx } = crear({ linea: linea({ extracto: { cuenta_id: CTA, cuenta: { moneda: 'PYG', activo: false } } }) });
    expect(await errorDe(promesa)).toMatchObject({ status: 400, codigo: 'CUENTA_INVALIDA' });
    expect(tx.tes_movimientos.create).not.toHaveBeenCalled();
    expect(tx.tes_cuentas.update).not.toHaveBeenCalled();
  });
  it('la cuenta se cierra entre la lectura y el bloqueo → 400 CUENTA_INVALIDA: manda lo leído bajo bloqueo', async () => {
    const { promesa, tx } = crear({ cuentaActivaEnTx: false });
    expect(await errorDe(promesa)).toMatchObject({ status: 400, codigo: 'CUENTA_INVALIDA' });
    expect(tx.tes_movimientos.create).not.toHaveBeenCalled();
  });
  it('cuenta y categoría se validan dentro del bloqueo: extracto, cuenta, categoría, guarda', async () => {
    const { promesa, orden } = crear();
    await promesa;
    const pos = ['bloqueo-extracto', 'bloqueo-cuenta', 'categorias.findMany', 'lineas.updateMany', 'movimiento.create'].map((n) => orden.indexOf(n));
    expect(pos.every((p) => p >= 0)).toBe(true);
    expect([...pos].sort((a, b) => a - b)).toEqual(pos);
  });
  it('línea con fecha de mañana (Asunción) → FECHA_FUTURA; con la de hoy, crea', async () => {
    const a = crear({ linea: linea({ fecha: new Date('2026-11-05T00:00:00.000Z') }) });
    expect(await errorDe(a.promesa)).toMatchObject({ status: 400, codigo: 'FECHA_FUTURA' });
    expect(a.prisma.$transaction).not.toHaveBeenCalled();
    await expect(crear({ linea: linea({ fecha: new Date('2026-11-04T00:00:00.000Z') }) }).promesa).resolves.toMatchObject({ ok: true });
  });
  it('línea en 0 → LINEA_SIN_MONTO', async () => {
    expect(await errorDe(crear({ linea: linea({ debito: dec(0), credito: dec(0) }) }).promesa)).toMatchObject({ status: 400, codigo: 'LINEA_SIN_MONTO' });
  });
  it('el umbral de aprobación no se lee: queda CONFIRMADO (fila 7)', async () => {
    const { promesa, tx, prisma } = crear();
    await promesa;
    expect(tx.tes_movimientos.create.mock.calls[0][0].data.estado).toBe('CONFIRMADO');
    expect((prisma as Record<string, unknown>).tes_config).toBeUndefined();
  });
  it('la guarda exige el importe y la fecha leídos: una edición simultánea da 409', async () => {
    const { promesa, tx } = crear();
    await promesa;
    const l = linea();
    expect(tx.tes_extracto_lineas.updateMany.mock.calls[0][0].where).toMatchObject({ debito: l.debito, credito: l.credito, fecha: l.fecha });
  });

  describe('un solo movimiento por importe: Crear → Desconciliar → Crear, o Eliminar → reimportar → Crear (I1)', () => {
    it('hay uno creado desde la conciliación sin línea conciliada → 400 MOVIMIENTO_YA_CREADO con su mensaje; no toca nada ni genera asiento', async () => {
      const { promesa, tx, contabilidad } = crear({ movimientoYaCreado: { id: MOV } });
      expect(await errorDe(promesa)).toMatchObject({
        status: 400,
        codigo: 'MOVIMIENTO_YA_CREADO',
        message: 'Ya hay un movimiento creado para este importe: conciliá la línea con él o anulalo en Movimientos',
      });
      expect(tx.tes_extracto_lineas.updateMany).not.toHaveBeenCalled();
      expect(tx.tes_movimientos.create).not.toHaveBeenCalled();
      expect(tx.tes_movimiento_det.create).not.toHaveBeenCalled();
      expect(tx.tes_cuentas.update).not.toHaveBeenCalled();
      expect(contabilidad.integrarMovimientoTesoreria).not.toHaveBeenCalled();
    });
    it('busca en la misma empresa, cuenta, tipo, monto y fecha, solo CONFIRMADO, de la conciliación y sin línea conciliada', async () => {
      const { promesa, tx } = crear({ linea: linea({ debito: dec(0), credito: dec(500) }) });
      await promesa;
      expect(tx.tes_movimientos.findFirst).toHaveBeenCalledWith({
        where: {
          empresa_id: EMP,
          cuenta_id: CTA,
          tipo: 'INGRESO',
          monto: 500,
          fecha: new Date('2026-10-20T00:00:00.000Z'),
          estado: 'CONFIRMADO',
          origen_tipo: 'CONCILIACION_AJUSTE',
          extracto_lineas: { none: { conciliado: true } },
        },
        select: { id: true },
      });
    });
    it('sin ninguno (la primera comisión igual ya está conciliada, o el anterior se anuló): crea', async () => {
      const { promesa, tx } = crear({ movimientoYaCreado: null });
      await expect(promesa).resolves.toMatchObject({ ok: true, movimiento_id: MOV });
      expect(tx.tes_movimientos.create).toHaveBeenCalledTimes(1);
    });
    it('se busca bajo el bloqueo de la cuenta, tras la categoría y antes de la guarda', async () => {
      const { promesa, orden } = crear();
      await promesa;
      const pos = ['bloqueo-cuenta', 'categorias.findMany', 'movimiento.yaCreado', 'lineas.updateMany', 'movimiento.create'].map((n) => orden.indexOf(n));
      expect(pos.every((p) => p >= 0)).toBe(true);
      expect([...pos].sort((a, b) => a - b)).toEqual(pos);
    });
    it('una categoría inválida se informa antes que el movimiento repetido', async () => {
      const { promesa } = crear({ movimientoYaCreado: { id: MOV }, categorias: [] });
      expect(await errorDe(promesa)).toMatchObject({ status: 400, codigo: 'CATEGORIA_INVALIDA' });
    });
  });

  describe('asiento (6.4)', () => {
    const conIntegrador = (fn: jest.Mock, e: Parameters<typeof armar>[0] = {}) => crear({ integrador: fn, ...e });
    it('generado → { generado: true, motivo: null }', async () => {
      expect((await conIntegrador(jest.fn().mockResolvedValue({ generado: true })).promesa).asiento).toEqual({ generado: true, motivo: null });
    });
    it('CATEGORIA_SIN_CUENTA lleva la categoría', async () => {
      expect((await conIntegrador(jest.fn().mockResolvedValue({ generado: false, motivo: 'CATEGORIA_SIN_CUENTA', categoria: 'X' })).promesa).asiento).toEqual({
        generado: false,
        motivo: 'CATEGORIA_SIN_CUENTA',
        categoria: 'X',
      });
    });
    it('SIN_MODULO pasa igual', async () => {
      expect((await conIntegrador(jest.fn().mockResolvedValue({ generado: false, motivo: 'SIN_MODULO' })).promesa).asiento).toEqual({ generado: false, motivo: 'SIN_MODULO' });
    });
    it.each(['CUENTA_SIN_CUENTA_CONTABLE', 'SIN_PERIODO_ABIERTO'])('%s pasa igual', async (motivo) => {
      expect((await conIntegrador(jest.fn().mockResolvedValue({ generado: false, motivo })).promesa).asiento).toEqual({ generado: false, motivo });
    });
    it('undefined con constancia → FALTA_MAPEO con sus conceptos', async () => {
      const { promesa, prisma } = conIntegrador(jest.fn().mockResolvedValue(undefined), { constancia: { new_value: { conceptos: ['BANCOS'] } } });
      expect((await promesa).asiento).toEqual({ generado: false, motivo: 'FALTA_MAPEO', conceptos: ['BANCOS'] });
      expect(prisma.audit_logs.findFirst.mock.calls[0][0].where).toMatchObject({ entity_type: 'tes_movimientos', entity_id: MOV, empresa_id: EMP });
    });
    it('lanza Error("boom") → ok, ERROR_INESPERADO sin mensaje, y la transacción una sola vez', async () => {
      const { promesa, prisma } = conIntegrador(jest.fn().mockRejectedValue(new Error('boom')));
      const r = await promesa;
      expect(r.ok).toBe(true);
      expect(r.asiento).toEqual({ generado: false, motivo: 'ERROR', codigo: 'ERROR_INESPERADO' });
      expect(JSON.stringify(r)).not.toContain('boom');
      expect(prisma.$transaction).toHaveBeenCalledTimes(1);
    });
    it('un error nuestro va con su código y mensaje', async () => {
      const r = await conIntegrador(jest.fn().mockRejectedValue(solicitudInvalida({ codigo: 'TIPO_CAMBIO_NO_REGISTRADO', message: 'Falta la cotización' }))).promesa;
      expect(r.asiento).toEqual({ generado: false, motivo: 'ERROR', codigo: 'TIPO_CAMBIO_NO_REGISTRADO', mensaje: 'Falta la cotización' });
    });
    it('se espera, después del commit', async () => {
      const a = armar();
      let integrado = false;
      a.contabilidad.integrarMovimientoTesoreria.mockImplementation(async () => {
        a.orden.push('integrar');
        await new Promise((r) => setImmediate(r));
        integrado = true;
        return { generado: true };
      });
      await a.service.crearMovimientoDesdeLinea(EMP, LIN, { categoria_id: CAT }, USER);
      expect(integrado).toBe(true);
      expect(a.orden.indexOf('extracto.update')).toBeLessThan(a.orden.indexOf('integrar'));
      expect(a.contabilidad.integrarMovimientoTesoreria).toHaveBeenCalledWith(MOV);
    });
    it('con la guarda en 0 no se llama al integrador', async () => {
      const a = armar({ guarda: 0 });
      await errorDe(a.service.crearMovimientoDesdeLinea(EMP, LIN, { categoria_id: CAT }, USER));
      expect(a.contabilidad.integrarMovimientoTesoreria).not.toHaveBeenCalled();
    });
  });
});

describe('contabilizarLinea (Reintentar)', () => {
  const conAjuste = (o: Record<string, unknown> = {}) =>
    linea({ conciliado: true, movimiento_id: MOV, movimiento: { id: MOV, estado: 'CONFIRMADO', origen_tipo: 'CONCILIACION_AJUSTE', ...o } });
  beforeEach(() => submodulo.mockReset().mockResolvedValue({ activo: true }));

  it('sin CONTABILIDAD_CONCILIACION → 403', async () => {
    submodulo.mockResolvedValue({ mensaje: 'Tu plan no incluye Conciliación' });
    const { service, contabilidad } = armar({ linea: conAjuste() });
    expect(await errorDe(service.contabilizarLinea(EMP, LIN))).toMatchObject({ status: 403 });
    expect(submodulo.mock.calls[0][2]).toBe('CONTABILIDAD_CONCILIACION');
    expect(contabilidad.integrarMovimientoTesoreria).not.toHaveBeenCalled();
  });
  it('conciliada con CONCILIACION_AJUSTE CONFIRMADO → llama al integrador y devuelve { contabilizada, asiento }', async () => {
    const { service, prisma, contabilidad } = armar({ linea: conAjuste(), documento: { id: 'd' } });
    expect(await service.contabilizarLinea(EMP, LIN)).toEqual({ contabilizada: true, asiento: { generado: true, motivo: null } });
    expect(contabilidad.integrarMovimientoTesoreria).toHaveBeenCalledWith(MOV);
    expect(prisma.cont_documentos.findFirst.mock.calls[0][0].where).toEqual({ empresa_id: EMP, origen_tipo: 'tes_movimientos', origen_id: MOV, estado: 'CONFIRMADO' });
  });
  it('CONCILIACION_AUTO también', async () => {
    await expect(armar({ linea: conAjuste({ origen_tipo: 'CONCILIACION_AUTO' }), documento: { id: 'd' } }).service.contabilizarLinea(EMP, LIN)).resolves.toMatchObject({
      contabilizada: true,
    });
  });
  it.each([
    ['sin movimiento', linea({ conciliado: false })],
    ['de un cheque', conAjuste({ origen_tipo: 'CHEQUE_DEPOSITADO' })],
    ['anulado', conAjuste({ estado: 'ANULADO' })],
    ['sin origen', conAjuste({ origen_tipo: null })],
  ])('línea %s → 400 LINEA_SIN_MOVIMIENTO', async (_n, l) => {
    const { service, contabilidad } = armar({ linea: l });
    expect(await errorDe(service.contabilizarLinea(EMP, LIN))).toMatchObject({ status: 400, codigo: 'LINEA_SIN_MOVIMIENTO' });
    expect(contabilidad.integrarMovimientoTesoreria).not.toHaveBeenCalled();
  });
  it('F16: el integrador dice generado pero solo hay un documento REVERTIDO → contabilizada false', async () => {
    const r = await armar({ linea: conAjuste(), documento: null }).service.contabilizarLinea(EMP, LIN);
    expect(r).toEqual({ contabilizada: false, asiento: { generado: true, motivo: null } });
  });
  it('el integrador lanza → ERROR_INESPERADO sin mensaje, contabilizada false', async () => {
    const r = await armar({ linea: conAjuste(), integrador: jest.fn().mockRejectedValue(new Error('boom')) }).service.contabilizarLinea(EMP, LIN);
    expect(r).toEqual({ contabilizada: false, asiento: { generado: false, motivo: 'ERROR', codigo: 'ERROR_INESPERADO' } });
  });
  it('id no UUID o ajena → 404', async () => {
    expect(await errorDe(armar().service.contabilizarLinea(EMP, 'abc'))).toMatchObject({ status: 404, codigo: 'LINEA_NO_ENCONTRADA' });
    expect(await errorDe(armar({ linea: null }).service.contabilizarLinea(EMP, LIN))).toMatchObject({ status: 404, codigo: 'LINEA_NO_ENCONTRADA' });
  });
});

describe('actualizarLinea', () => {
  const conMoneda = (moneda: string) => linea({ extracto: { cuenta_id: CTA, cuenta: { moneda, activo: true } } });
  it('cuenta PYG con decimales → 400 MONTO_INVALIDO con el campo', async () => {
    expect(await errorDe(armar().service.actualizarLinea(EMP, LIN, { debito: 1500.5 }))).toMatchObject({ status: 400, codigo: 'MONTO_INVALIDO', campo: 'debito' });
    expect(await errorDe(armar().service.actualizarLinea(EMP, LIN, { credito: 1500.5 }))).toMatchObject({ status: 400, codigo: 'MONTO_INVALIDO', campo: 'credito' });
  });
  it('cuenta USD: guarda 1500.5, el otro lado en 0, y devuelve números', async () => {
    const { service, tx } = armar({ linea: conMoneda('USD') });
    tx.tes_extracto_lineas.findFirst.mockResolvedValue(linea({ debito: dec(1500.5), saldo: dec(7) }));
    const r = await service.actualizarLinea(EMP, LIN, { debito: 1500.5 });
    expect(tx.tes_extracto_lineas.updateMany.mock.calls[0][0].data).toEqual({ debito: 1500.5, credito: 0 });
    expect(r).toMatchObject({ debito: 1500.5, credito: 0, saldo: 7 });
  });
  it('importe en 0 → MONTO_INVALIDO', async () => {
    expect(await errorDe(armar().service.actualizarLinea(EMP, LIN, { debito: 0 }))).toMatchObject({ status: 400, codigo: 'MONTO_INVALIDO', campo: 'debito' });
  });
  it('fecha de mañana → FECHA_FUTURA; la de hoy pasa como fecha DATE', async () => {
    expect(await errorDe(armar().service.actualizarLinea(EMP, LIN, { fecha: '2026-11-05' }))).toMatchObject({ status: 400, codigo: 'FECHA_FUTURA', campo: 'fecha' });
    const { service, tx } = armar();
    await service.actualizarLinea(EMP, LIN, { fecha: '2026-11-04' });
    expect(tx.tes_extracto_lineas.updateMany.mock.calls[0][0].data).toEqual({ fecha: new Date('2026-11-04T00:00:00.000Z') });
  });
  it('sin campos → SIN_CAMBIOS', async () => {
    const { service, prisma } = armar();
    expect(await errorDe(service.actualizarLinea(EMP, LIN, {}))).toMatchObject({ status: 400, codigo: 'SIN_CAMBIOS' });
    expect(prisma.$transaction).not.toHaveBeenCalled();
  });
  it('débito y crédito juntos → 400 MONTO_INVALIDO', async () => {
    expect(await errorDe(armar().service.actualizarLinea(EMP, LIN, { debito: 100, credito: 100 }))).toMatchObject({ status: 400, codigo: 'MONTO_INVALIDO' });
  });
});

describe('eliminarExtracto (C8)', () => {
  it('con líneas CONCILIACION_* → 400 EXTRACTO_CON_MOVIMIENTOS con la cantidad; deleteMany no se llama', async () => {
    const { service, tx } = armar({ conConciliacion: 1 });
    const e = await errorDe(service.eliminarExtracto(EMP, EXT));
    expect(e).toMatchObject({ status: 400, codigo: 'EXTRACTO_CON_MOVIMIENTOS', cantidad: 1 });
    expect(e!.message).toContain('1');
    expect(tx.tes_extracto_bancario.deleteMany).not.toHaveBeenCalled();
  });
  it('cuenta en el tx, tras el FOR UPDATE: conciliadas con movimiento CONFIRMADO de origen CONCILIACION_* (AJUSTE y AUTO)', async () => {
    const { service, tx, orden } = armar();
    await service.eliminarExtracto(EMP, EXT);
    expect(orden.indexOf('bloqueo-extracto')).toBeLessThan(orden.indexOf('lineas.count'));
    expect(orden.indexOf('lineas.count')).toBeLessThan(orden.indexOf('extracto.deleteMany'));
    expect(tx.tes_extracto_lineas.count.mock.calls[0][0].where).toEqual({
      extracto_id: EXT,
      conciliado: true,
      movimiento: { estado: 'CONFIRMADO', origen_tipo: { in: ['CONCILIACION_AJUSTE', 'CONCILIACION_AUTO'] } },
    });
  });
  it('sin ellas (anulado, sin origen, de un cheque) borra por id y empresa, y tes_movimientos no se toca', async () => {
    const { service, tx } = armar({ conConciliacion: 0 });
    await expect(service.eliminarExtracto(EMP, EXT)).resolves.toEqual({ ok: true });
    expect(tx.tes_extracto_bancario.deleteMany).toHaveBeenCalledWith({ where: { id: EXT, empresa_id: EMP } });
    expect(tx.tes_movimientos.create).not.toHaveBeenCalled();
    expect(tx.tes_cuentas.update).not.toHaveBeenCalled();
  });
  it('ajeno o no UUID → 404 EXTRACTO_NO_ENCONTRADO', async () => {
    expect(await errorDe(armar({ extracto: null }).service.eliminarExtracto(EMP, EXT))).toMatchObject({ status: 404, codigo: 'EXTRACTO_NO_ENCONTRADO' });
    const a = armar();
    expect(await errorDe(a.service.eliminarExtracto(EMP, 'abc'))).toMatchObject({ status: 404, codigo: 'EXTRACTO_NO_ENCONTRADO' });
    expect(a.prisma.$transaction).not.toHaveBeenCalled();
  });
});
