import { HttpException } from '@nestjs/common';
import { submoduloHabilitado } from '../../auth/guards/submodulo.guard';
import { noEncontrado, solicitudInvalida } from '../../common/utils/error-estructurado';
import { isContabilidadEnabledForEmpresa } from '../../common/utils/module-access.util';
import { TesTransferenciasService } from './tes-transferencias.service';

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

const EMP = 'emp-1';
const USER = 'u-1';
const TRF = '11111111-1111-4111-8111-111111111111';
const TRF2 = '22222222-2222-4222-8222-222222222222';
const C_PYG = '33333333-3333-4333-8333-333333333333';
const C_USD = '44444444-4444-4444-8444-444444444444';
const C_BRL = '55555555-5555-4555-8555-555555555555';

const CUENTAS: Record<string, any> = {
  [C_PYG]: { id: C_PYG, nombre: 'DOBA S.A.', moneda: 'PYG', activo: true },
  [C_USD]: { id: C_USD, nombre: 'DOBA S.A. DOLARES', moneda: 'USD', activo: true },
  [C_BRL]: { id: C_BRL, nombre: 'E2E BRL', moneda: 'BRL', activo: true },
};

const movTrf = (o: Record<string, unknown> = {}) => ({
  id: 'mo-1',
  empresa_id: EMP,
  cuenta_id: C_PYG,
  tipo: 'TRANSFERENCIA',
  estado: 'CONFIRMADO',
  fecha: new Date('2026-05-05'),
  monto: 7300000,
  tipo_cambio: 7300,
  descripcion: 'Compra de dólares',
  transferencia_id: TRF,
  origen_tipo: 'TRANSFERENCIA_ORIGEN',
  created_by: USER,
  confirmado_por: USER,
  confirmado_en: new Date('2026-05-05T10:00:00Z'),
  anulado_por: null,
  anulado_en: null,
  motivo_anulacion: null,
  created_at: new Date('2026-05-05T10:00:00Z'),
  cuenta: { id: C_PYG, nombre: 'DOBA S.A.', moneda: 'PYG', activo: true },
  ...o,
});
const origen1 = (o: Record<string, unknown> = {}) => movTrf(o);
const destino1 = (o: Record<string, unknown> = {}) =>
  movTrf({
    id: 'md-1',
    cuenta_id: C_USD,
    monto: 1000,
    origen_tipo: 'TRANSFERENCIA_DESTINO',
    cuenta: { id: C_USD, nombre: 'DOBA S.A. DOLARES', moneda: 'USD', activo: true },
    ...o,
  });

interface Opciones {
  /** Lo que devuelve `tes_movimientos.findMany` según el `where`. */
  movimientos?: any[];
  conciliadas?: string[];
  /** Línea conciliada al releer dentro del tx (otro usuario concilió entre medio). */
  conciliadaEnTx?: boolean;
  documentos?: string[];
  updateMany?: number;
  integrador?: () => Promise<unknown>;
  constancia?: Record<string, unknown> | null;
  vigente?: Record<string, unknown>;
}

/** Filtra los movimientos del mock como lo haría Prisma con los `where` que usa el servicio. */
const coincide = (m: any, w: any): boolean => {
  if (!w) return true;
  if (w.empresa_id && m.empresa_id !== w.empresa_id) return false;
  if (w.cuenta_id && m.cuenta_id !== w.cuenta_id) return false;
  if (w.estado && m.estado !== w.estado) return false;
  if (typeof w.origen_tipo === 'string' && m.origen_tipo !== w.origen_tipo) return false;
  if (w.origen_tipo?.in && !w.origen_tipo.in.includes(m.origen_tipo)) return false;
  if (typeof w.transferencia_id === 'string' && m.transferencia_id !== w.transferencia_id) return false;
  if (w.transferencia_id?.in && !w.transferencia_id.in.includes(m.transferencia_id)) return false;
  return true;
};

function armar(o: Opciones = {}) {
  const movimientos = o.movimientos ?? [origen1(), destino1()];
  const tx: any = {
    tes_movimientos: {
      // Lo creado queda en la lista del mock: el alta relee la fila con findOne.
      create: jest.fn().mockImplementation(({ data }: any) => {
        const m = { ...movTrf(), cuenta: CUENTAS[data.cuenta_id], id: data.origen_tipo === 'TRANSFERENCIA_ORIGEN' ? 'mo-n' : 'md-n', ...data };
        movimientos.push(m);
        return Promise.resolve(m);
      }),
      updateMany: jest.fn().mockResolvedValue({ count: o.updateMany ?? movimientos.length }),
    },
    $queryRaw: jest.fn().mockResolvedValue([]),
    tes_cuentas: { update: jest.fn().mockResolvedValue({}) },
    tes_extracto_lineas: { findFirst: jest.fn().mockResolvedValue(o.conciliadaEnTx ? { id: 'l-tx' } : null) },
  };
  const prisma: any = {
    $transaction: jest.fn().mockImplementation((cb: any) => cb(tx)),
    tes_movimientos: { findMany: jest.fn().mockImplementation(({ where }: any) => Promise.resolve(movimientos.filter((m) => coincide(m, where)))) },
    tes_cuentas: { findFirst: jest.fn().mockImplementation(({ where }: any) => Promise.resolve(CUENTAS[where.id] ?? null)), findMany: jest.fn().mockResolvedValue([]) },
    tes_extracto_lineas: {
      findMany: jest.fn().mockImplementation(() => Promise.resolve((o.conciliadas ?? []).map((movimiento_id) => ({ movimiento_id })))),
      findFirst: jest.fn().mockImplementation(({ where }: any) => Promise.resolve((o.conciliadas ?? []).some((id) => where.movimiento_id.in.includes(id)) ? { id: 'l-1' } : null)),
    },
    cont_documentos: {
      findMany: jest.fn().mockImplementation(() => Promise.resolve((o.documentos ?? []).map((origen_id) => ({ origen_id })))),
      findFirst: jest.fn().mockImplementation(() => Promise.resolve((o.documentos ?? []).length ? { id: 'doc-1' } : null)),
    },
    audit_logs: { findFirst: jest.fn().mockResolvedValue(o.constancia ?? null) },
  };
  const integracion: any = {
    integrarTransferenciaTes: jest.fn().mockImplementation(o.integrador ?? (() => Promise.resolve({ generado: true }))),
    revertirDocumento: jest.fn().mockResolvedValue(undefined),
  };
  const audit: any = { log: jest.fn().mockResolvedValue(undefined) };
  const monedas: any = { getCotizacionVigente: jest.fn().mockResolvedValue(o.vigente ?? { tasa: 7300, fuente: 'contabilidad', fecha_efectiva: '05/05/2026' }) };
  return { prisma, tx, integracion, audit, monedas, servicio: new TesTransferenciasService(prisma, integracion, audit, monedas) };
}

const falla = async (p: Promise<unknown>) => {
  try {
    await p;
  } catch (e: any) {
    if (!(e instanceof HttpException)) throw e;
    const r = e.getResponse() as Record<string, unknown>;
    return { status: e.getStatus(), ...(typeof r === 'string' ? { message: r } : r) } as Record<string, any>;
  }
  throw new Error('no lanzó');
};

beforeEach(() => {
  contabilidad.mockReset().mockResolvedValue(true);
  submodulo.mockReset().mockResolvedValue({ habilitado: true, fechaFinPrueba: null });
});

describe('listado', () => {
  it('sin filtros: los movimientos origen de transferencias de la empresa, por fecha y alta descendentes', async () => {
    const { prisma, servicio } = armar();
    await servicio.findAll(EMP, {});
    const args = prisma.tes_movimientos.findMany.mock.calls[0][0];
    expect(args.where).toEqual({ empresa_id: EMP, tipo: 'TRANSFERENCIA', origen_tipo: 'TRANSFERENCIA_ORIGEN' });
    expect(args.orderBy).toEqual([{ fecha: 'desc' }, { created_at: 'desc' }]);
  });

  it('cuenta_id: primero busca las transferencias por cualquiera de las dos puntas; una que ENTRA a la cuenta aparece (D4)', async () => {
    const entra = [origen1({ id: 'mo-2', transferencia_id: TRF2 }), destino1({ id: 'md-2', transferencia_id: TRF2 })];
    const sale = [origen1({ cuenta_id: C_USD }), destino1({ cuenta_id: C_PYG })];
    const { prisma, servicio } = armar({ movimientos: [...sale, ...entra] });
    const filas = await servicio.findAll(EMP, { cuenta_id: C_USD });
    const [puntas, origenes] = prisma.tes_movimientos.findMany.mock.calls.map((c: any) => c[0]);
    expect(puntas.where).toEqual({ empresa_id: EMP, cuenta_id: C_USD, origen_tipo: { in: ['TRANSFERENCIA_ORIGEN', 'TRANSFERENCIA_DESTINO'] }, transferencia_id: { not: null } });
    expect(origenes.where).toMatchObject({ empresa_id: EMP, origen_tipo: 'TRANSFERENCIA_ORIGEN', transferencia_id: { in: [TRF, TRF2] } });
    expect(origenes.where).not.toHaveProperty('cuenta_id');
    expect(filas.map((f) => f.id).sort()).toEqual([TRF, TRF2]);
  });

  it('una cuenta sin transferencias no consulta más', async () => {
    const { prisma, servicio } = armar({ movimientos: [] });
    expect(await servicio.findAll(EMP, { cuenta_id: C_BRL })).toEqual([]);
    expect(prisma.tes_movimientos.findMany).toHaveBeenCalledTimes(1);
  });

  it('desde/hasta van a fecha; estado tal cual', async () => {
    const { prisma, servicio } = armar();
    await servicio.findAll(EMP, { desde: '2026-05-01', hasta: '2026-05-31', estado: 'ANULADO' });
    expect(prisma.tes_movimientos.findMany.mock.calls[0][0].where).toMatchObject({ fecha: { gte: new Date('2026-05-01'), lte: new Date('2026-05-31') }, estado: 'ANULADO' });
  });

  it('una línea de extracto conciliada en el movimiento destino → conciliado: true', async () => {
    const { prisma, servicio } = armar({ conciliadas: ['md-1'] });
    const [fila] = await servicio.findAll(EMP, {});
    expect(fila.conciliado).toBe(true);
    expect(prisma.tes_extracto_lineas.findMany.mock.calls[0][0].where).toEqual({ movimiento_id: { in: ['mo-1', 'md-1'] }, conciliado: true });
  });

  it('con CONTABILIDAD: contabilizada según el documento CONFIRMADO de tes_transferencias', async () => {
    const movs = [origen1(), destino1(), origen1({ id: 'mo-2', transferencia_id: TRF2 }), destino1({ id: 'md-2', transferencia_id: TRF2 })];
    const { prisma, servicio } = armar({ movimientos: movs, documentos: [TRF] });
    const filas = await servicio.findAll(EMP, {});
    expect(filas.find((f) => f.id === TRF)!.contabilizada).toBe(true);
    expect(filas.find((f) => f.id === TRF2)!.contabilizada).toBe(false);
    expect(prisma.cont_documentos.findMany.mock.calls[0][0].where).toEqual({
      empresa_id: EMP,
      origen_tipo: 'tes_transferencias',
      origen_id: { in: [TRF, TRF2] },
      estado: 'CONFIRMADO',
    });
  });

  it('sin CONTABILIDAD: contabilizada null y no se consultan documentos', async () => {
    contabilidad.mockResolvedValue(false);
    const { prisma, servicio } = armar({ documentos: [TRF] });
    const [fila] = await servicio.findAll(EMP, {});
    expect(fila.contabilizada).toBeNull();
    expect(prisma.cont_documentos.findMany).not.toHaveBeenCalled();
  });

  it('la fila completa: cuentas con { id, nombre, moneda, activo }, montos y tipo de cambio como número', async () => {
    const { servicio } = armar();
    const [fila] = await servicio.findAll(EMP, {});
    expect(fila).toEqual({
      id: TRF,
      estado: 'CONFIRMADO',
      fecha: new Date('2026-05-05'),
      descripcion: 'Compra de dólares',
      monto_origen: 7300000,
      cuenta_origen: { id: C_PYG, nombre: 'DOBA S.A.', moneda: 'PYG', activo: true },
      cuenta_destino: { id: C_USD, nombre: 'DOBA S.A. DOLARES', moneda: 'USD', activo: true },
      monto_destino: 1000,
      tipo_cambio: 7300,
      movimiento_origen_id: 'mo-1',
      movimiento_destino_id: 'md-1',
      created_by: USER,
      confirmado_por: USER,
      confirmado_en: new Date('2026-05-05T10:00:00Z'),
      anulado_por: null,
      anulado_en: null,
      motivo_anulacion: null,
      conciliado: false,
      contabilizada: false,
    });
  });

  it('tipo_cambio nulo (las multimoneda viejas) queda null', async () => {
    const { servicio } = armar({ movimientos: [origen1({ tipo_cambio: null }), destino1({ tipo_cambio: null })] });
    const [fila] = await servicio.findAll(EMP, {});
    expect(fila.tipo_cambio).toBeNull();
  });
});

describe('opciones', () => {
  it('las cuentas de la empresa con su saldo como número, activas primero y por nombre', async () => {
    const { prisma, servicio } = armar();
    prisma.tes_cuentas.findMany.mockResolvedValue([
      { id: C_PYG, nombre: 'DOBA S.A.', moneda: 'PYG', tipo: 'BANCO_CC', activo: true, saldo_actual: { toString: () => '229638812.56' } },
    ]);
    const r = await servicio.opciones(EMP);
    expect(r).toEqual({ cuentas: [{ id: C_PYG, nombre: 'DOBA S.A.', moneda: 'PYG', tipo: 'BANCO_CC', activo: true, saldo_actual: 229638812.56 }] });
    expect(prisma.tes_cuentas.findMany.mock.calls[0][0]).toEqual({
      where: { empresa_id: EMP },
      select: { id: true, nombre: true, moneda: true, tipo: true, activo: true, saldo_actual: true },
      orderBy: [{ activo: 'desc' }, { nombre: 'asc' }],
    });
  });
});

describe('detalle', () => {
  it('sin movimientos → 404 TRANSFERENCIA_NO_ENCONTRADA', async () => {
    const { servicio } = armar({ movimientos: [] });
    expect(await falla(servicio.findOne(TRF, EMP))).toMatchObject({ status: 404, codigo: 'TRANSFERENCIA_NO_ENCONTRADA' });
  });
  it('con sus dos movimientos → la misma fila que el listado', async () => {
    const { servicio } = armar();
    const [deLista] = await servicio.findAll(EMP, {});
    expect(await servicio.findOne(TRF, EMP)).toEqual(deLista);
  });
});

describe('alta', () => {
  const dto = (o: Record<string, unknown> = {}) => ({ cuenta_origen_id: C_PYG, cuenta_destino_id: C_USD, monto: 7300000, fecha: '2026-05-05', tipo_cambio: 7300, ...o }) as any;

  it('origen = destino → 400 CUENTAS_IGUALES en el destino, sin abrir la transacción', async () => {
    const { prisma, servicio } = armar();
    expect(await falla(servicio.create(dto({ cuenta_destino_id: C_PYG }), EMP, USER))).toMatchObject({ status: 400, codigo: 'CUENTAS_IGUALES', campo: 'cuenta_destino_id' });
    expect(prisma.$transaction).not.toHaveBeenCalled();
  });

  it('origen inexistente o cerrada → 400 CUENTA_INVALIDA en el origen; el destino en el destino', async () => {
    const { servicio } = armar();
    const OTRA = '66666666-6666-4666-8666-666666666666';
    expect(await falla(servicio.create(dto({ cuenta_origen_id: OTRA }), EMP, USER))).toMatchObject({ status: 400, codigo: 'CUENTA_INVALIDA', campo: 'cuenta_origen_id' });
    expect(await falla(servicio.create(dto({ cuenta_destino_id: OTRA }), EMP, USER))).toMatchObject({ status: 400, codigo: 'CUENTA_INVALIDA', campo: 'cuenta_destino_id' });
  });

  it('las cuentas se buscan activas y de la empresa', async () => {
    const { prisma, servicio } = armar();
    await servicio.create(dto(), EMP, USER);
    expect(prisma.tes_cuentas.findFirst.mock.calls[0][0].where).toEqual({ id: C_PYG, empresa_id: EMP, activo: true });
  });

  it('USD → BRL → 400 TRANSFERENCIA_ENTRE_EXTRANJERAS (D6)', async () => {
    const { prisma, servicio } = armar();
    expect(await falla(servicio.create(dto({ cuenta_origen_id: C_USD, cuenta_destino_id: C_BRL, monto: 100 }), EMP, USER))).toMatchObject({
      status: 400,
      codigo: 'TRANSFERENCIA_ENTRE_EXTRANJERAS',
    });
    expect(prisma.$transaction).not.toHaveBeenCalled();
  });

  it('PYG → USD sin tipo de cambio → 400 TIPO_CAMBIO_REQUERIDO', async () => {
    const { servicio } = armar();
    expect(await falla(servicio.create(dto({ tipo_cambio: undefined }), EMP, USER))).toMatchObject({ status: 400, codigo: 'TIPO_CAMBIO_REQUERIDO', campo: 'tipo_cambio' });
    expect(await falla(servicio.create(dto({ tipo_cambio: 0 }), EMP, USER))).toMatchObject({ codigo: 'TIPO_CAMBIO_REQUERIDO' });
  });

  it('PYG → USD con 730 contra 7.300 de contabilidad → 400 TIPO_CAMBIO_FUERA_DE_RANGO con la referencia', async () => {
    const { prisma, servicio } = armar();
    const r = await falla(servicio.create(dto({ tipo_cambio: 730 }), EMP, USER));
    expect(r).toMatchObject({ status: 400, codigo: 'TIPO_CAMBIO_FUERA_DE_RANGO', campo: 'tipo_cambio', referencia: 7300, fecha_referencia: '05/05/2026' });
    expect(r.message).toContain('muy lejos de la cotización');
    expect(prisma.$transaction).not.toHaveBeenCalled();
  });

  it('con fuente fallback no se controla', async () => {
    const { prisma, servicio } = armar({ vigente: { tasa: 1, fuente: 'fallback', fecha_efectiva: null } });
    await servicio.create(dto({ tipo_cambio: 730 }), EMP, USER);
    expect(prisma.$transaction).toHaveBeenCalledTimes(1);
  });

  it('PYG → USD de 1.000.000 a 7.300: el destino y su saldo por US$ 136,99; el origen baja 1.000.000 (D8)', async () => {
    const { tx, servicio } = armar();
    await servicio.create(dto({ monto: 1000000 }), EMP, USER);
    const [mo, md] = tx.tes_movimientos.create.mock.calls.map((c: any) => c[0].data);
    expect(mo).toMatchObject({ cuenta_id: C_PYG, monto: 1000000, tipo_cambio: 7300, origen_tipo: 'TRANSFERENCIA_ORIGEN', estado: 'CONFIRMADO' });
    expect(md).toMatchObject({ cuenta_id: C_USD, monto: 136.99, tipo_cambio: 7300, origen_tipo: 'TRANSFERENCIA_DESTINO', estado: 'CONFIRMADO' });
    expect(tx.tes_cuentas.update).toHaveBeenCalledWith({ where: { id: C_PYG }, data: { saldo_actual: { increment: -1000000 } } });
    expect(tx.tes_cuentas.update).toHaveBeenCalledWith({ where: { id: C_USD }, data: { saldo_actual: { increment: 136.99 } } });
  });

  it('misma moneda: sin tipo de cambio guardado aunque venga', async () => {
    const OTRA_PYG = '77777777-7777-4777-8777-777777777777';
    CUENTAS[OTRA_PYG] = { id: OTRA_PYG, nombre: 'Otra Gs', moneda: 'PYG', activo: true };
    const { tx, monedas, servicio } = armar();
    await servicio.create(dto({ cuenta_destino_id: OTRA_PYG, monto: 5000 }), EMP, USER);
    const [mo, md] = tx.tes_movimientos.create.mock.calls.map((c: any) => c[0].data);
    expect(mo.tipo_cambio).toBeNull();
    expect(md).toMatchObject({ monto: 5000, tipo_cambio: null });
    expect(monedas.getCotizacionVigente).not.toHaveBeenCalled();
    delete CUENTAS[OTRA_PYG];
  });

  describe('el asiento se espera y va en la respuesta (A6)', () => {
    const crear = async (o: Opciones) => {
      const h = armar({ movimientos: [], ...o });
      const r: any = await h.servicio.create(dto(), EMP, USER);
      return { ...h, r };
    };

    it('{ generado: true } → asiento { generado: true, motivo: null }, llamado con los dos movimientos', async () => {
      const { r, integracion } = await crear({});
      expect(r.asiento).toEqual({ generado: true, motivo: null });
      expect(integracion.integrarTransferenciaTes).toHaveBeenCalledWith('mo-n', 'md-n', r.id, EMP);
    });
    it('SIN_MODULO pasa igual', async () => {
      const { r } = await crear({ integrador: () => Promise.resolve({ generado: false, motivo: 'SIN_MODULO' }) });
      expect(r.asiento).toEqual({ generado: false, motivo: 'SIN_MODULO' });
    });
    it('CUENTA_SIN_CUENTA_CONTABLE conserva la cuenta', async () => {
      const { r } = await crear({ integrador: () => Promise.resolve({ generado: false, motivo: 'CUENTA_SIN_CUENTA_CONTABLE', cuenta: 'DOBA S.A. DOLARES' }) });
      expect(r.asiento).toEqual({ generado: false, motivo: 'CUENTA_SIN_CUENTA_CONTABLE', cuenta: 'DOBA S.A. DOLARES' });
    });
    it('SIN_PERIODO_ABIERTO', async () => {
      const { r } = await crear({ integrador: () => Promise.resolve({ generado: false, motivo: 'SIN_PERIODO_ABIERTO' }) });
      expect(r.asiento).toEqual({ generado: false, motivo: 'SIN_PERIODO_ABIERTO' });
    });
    it('undefined (falta de mapeo) → FALTA_MAPEO con los conceptos de la constancia de tes_transferencias', async () => {
      const { r, prisma } = await crear({ integrador: () => Promise.resolve(undefined), constancia: { new_value: { conceptos: ['DIFERENCIA_CAMBIO_PERDIDA'] } } });
      expect(r.asiento).toEqual({ generado: false, motivo: 'FALTA_MAPEO', conceptos: ['DIFERENCIA_CAMBIO_PERDIDA'] });
      expect(prisma.audit_logs.findFirst.mock.calls[0][0].where).toEqual({ empresa_id: EMP, action: 'CONT_FALTA_MAPEO', entity_type: 'tes_transferencias', entity_id: r.id });
    });
    it('el integrador lanza Error("boom") → 201 con asiento ERROR y la transacción commiteada una vez', async () => {
      const { r, prisma, tx } = await crear({ integrador: () => Promise.reject(new Error('boom')) });
      // Ronda 1 (Minor 4): lo inesperado no llega crudo al cliente; queda en el log con su contexto.
      expect(r.asiento).toEqual({ generado: false, motivo: 'ERROR', codigo: 'ERROR_INESPERADO' });
      expect(prisma.$transaction).toHaveBeenCalledTimes(1);
      expect(tx.tes_cuentas.update).toHaveBeenCalledTimes(2);
      expect(r.estado).toBe('CONFIRMADO');
    });
    it('un error de Prisma no expone tablas ni columnas: solo ERROR_INESPERADO, y el detalle va al log con la transferencia', async () => {
      const { r, servicio } = await crear({
        integrador: () => Promise.reject(new Error('Invalid `tx.cont_asientos.create()` invocation: column "numero" of relation "cont_asientos"')),
      });
      expect(r.asiento).toEqual({ generado: false, motivo: 'ERROR', codigo: 'ERROR_INESPERADO' });
      expect(JSON.stringify(r.asiento)).not.toContain('cont_asientos');
      const log = jest.spyOn((servicio as any).logger, 'error');
      await servicio.create(dto(), EMP, USER).catch(() => undefined);
      expect(log.mock.calls[0][0]).toMatch(/transferencia .+ \(empresa emp-1, movimientos mo-n \/ md-n\)/);
    });
    it('un error con codigo conocido (TIPO_CAMBIO_NO_REGISTRADO) va con su codigo y su mensaje', async () => {
      const mensaje = 'No hay tipo de cambio registrado para USD en la fecha 2026-05-05';
      const { r } = await crear({ integrador: () => Promise.reject(noEncontrado({ message: mensaje, codigo: 'TIPO_CAMBIO_NO_REGISTRADO' })) });
      expect(r.asiento).toEqual({ generado: false, motivo: 'ERROR', codigo: 'TIPO_CAMBIO_NO_REGISTRADO', mensaje });
    });
    it('la auditoría formatea el monto con locale es-PY (no el del servidor)', async () => {
      const { audit } = await crear({});
      expect(audit.log.mock.calls[0][0].descripcion).toBe('Transferencia DOBA S.A. → DOBA S.A. DOLARES por 7.300.000 PYG');
    });
    it('la respuesta es la fila completa (tipo_cambio, confirmado_en, conciliado: false)', async () => {
      const { r, audit } = await crear({});
      expect(r).toMatchObject({ estado: 'CONFIRMADO', tipo_cambio: 7300, conciliado: false, movimiento_origen_id: 'mo-n', movimiento_destino_id: 'md-n' });
      expect(r.confirmado_en).toBeInstanceOf(Date);
      expect(audit.log).toHaveBeenCalledWith(expect.objectContaining({ action: 'TES_TRANSFERENCIA_CREADA', entity_type: 'tes_transferencias', entity_id: r.id }));
    });
  });
});

describe('anular', () => {
  const dto = { motivo: 'Error de carga' };

  it('sin movimientos → 404 TRANSFERENCIA_NO_ENCONTRADA', async () => {
    const { servicio } = armar({ movimientos: [] });
    expect(await falla(servicio.anular(TRF, dto, EMP, USER))).toMatchObject({ status: 404, codigo: 'TRANSFERENCIA_NO_ENCONTRADA' });
  });

  it('con CONTABILIDAD: en una transacción anula con guarda, revierte los dos saldos y el asiento', async () => {
    const { tx, integracion, servicio } = armar();
    const r = await servicio.anular(TRF, dto, EMP, USER);
    const um = tx.tes_movimientos.updateMany.mock.calls[0][0];
    expect(um.where).toEqual({ transferencia_id: TRF, empresa_id: EMP, estado: 'CONFIRMADO', extracto_lineas: { none: { conciliado: true } } });
    expect(um.data).toMatchObject({ estado: 'ANULADO', motivo_anulacion: 'Error de carga', anulado_por: USER });
    expect(um.data.anulado_en).toBeInstanceOf(Date);
    expect(tx.tes_cuentas.update).toHaveBeenCalledWith({ where: { id: C_PYG }, data: { saldo_actual: { increment: 7300000 } } });
    expect(tx.tes_cuentas.update).toHaveBeenCalledWith({ where: { id: C_USD }, data: { saldo_actual: { increment: -1000 } } });
    expect(integracion.revertirDocumento).toHaveBeenCalledTimes(1);
    expect(integracion.revertirDocumento).toHaveBeenCalledWith('tes_transferencias', TRF, USER, tx);
    expect(r).toMatchObject({ id: TRF });
  });

  it('bloquea las dos puntas por id (ORDER BY id FOR UPDATE) antes del updateMany, mismo orden que el asiento (m3)', async () => {
    const { tx, servicio } = armar();
    await servicio.anular(TRF, dto, EMP, USER);
    expect(tx.$queryRaw).toHaveBeenCalledTimes(1);
    const sql = (tx.$queryRaw.mock.calls[0][0] as string[]).join('?');
    expect(sql).toMatch(/transferencia_id = \?::uuid/);
    expect(sql).toMatch(/ORDER BY id\s+FOR UPDATE/);
    expect(tx.$queryRaw.mock.calls[0].slice(1)).toEqual([TRF, EMP]);
    expect(tx.$queryRaw.mock.invocationCallOrder[0]).toBeLessThan(tx.tes_movimientos.updateMany.mock.invocationCallOrder[0]);
  });

  it('updateMany cuenta 0 → 409 ESTADO_CAMBIADO, sin saldos ni reversión', async () => {
    const { tx, integracion, servicio } = armar({ updateMany: 0 });
    expect(await falla(servicio.anular(TRF, dto, EMP, USER))).toMatchObject({ status: 409, codigo: 'ESTADO_CAMBIADO' });
    expect(tx.tes_cuentas.update).not.toHaveBeenCalled();
    expect(integracion.revertirDocumento).not.toHaveBeenCalled();
  });

  it('updateMany cuenta 1 con 2 movimientos leídos → 409 dentro de la transacción', async () => {
    const { prisma, tx, servicio } = armar({ updateMany: 1 });
    expect(await falla(servicio.anular(TRF, dto, EMP, USER))).toMatchObject({ status: 409, codigo: 'ESTADO_CAMBIADO' });
    expect(prisma.$transaction).toHaveBeenCalledTimes(1);
    expect(tx.tes_cuentas.update).not.toHaveBeenCalled();
  });

  it('ya anulada (lectura previa) → 409 ESTADO_CAMBIADO sin abrir la transacción', async () => {
    const { prisma, servicio } = armar({ movimientos: [origen1({ estado: 'ANULADO' }), destino1({ estado: 'ANULADO' })] });
    expect(await falla(servicio.anular(TRF, dto, EMP, USER))).toMatchObject({ status: 409, codigo: 'ESTADO_CAMBIADO' });
    expect(prisma.$transaction).not.toHaveBeenCalled();
  });

  it('con CONTABILIDAD y el período cerrado → 400 ASIENTO_NO_REVERTIDO con el mensaje de asientos, y la transacción propaga', async () => {
    const mensaje = 'No se puede revertir: el período 05/2026 del asiento está CERRADO. Reabra ese período para revertirlo o registre un ajuste en el período actual.';
    const { integracion, prisma, servicio } = armar();
    integracion.revertirDocumento.mockRejectedValue(solicitudInvalida({ codigo: 'PERIODO_NO_ABIERTO', message: mensaje }));
    expect(await falla(servicio.anular(TRF, dto, EMP, USER))).toMatchObject({ status: 400, codigo: 'ASIENTO_NO_REVERTIDO', message: mensaje });
    await expect(prisma.$transaction.mock.results[0].value).rejects.toBeDefined();
  });

  it('con CONTABILIDAD y otro error al revertir → sale tal cual', async () => {
    const { integracion, servicio } = armar();
    integracion.revertirDocumento.mockRejectedValue(new Error('se cayó'));
    await expect(servicio.anular(TRF, dto, EMP, USER)).rejects.toThrow('se cayó');
  });

  it('sin CONTABILIDAD: anula y no llama a revertirDocumento (aunque fallaría)', async () => {
    contabilidad.mockResolvedValue(false);
    const { integracion, tx, servicio } = armar();
    integracion.revertirDocumento.mockRejectedValue(solicitudInvalida({ codigo: 'PERIODO_NO_ABIERTO', message: 'cerrado' }));
    await servicio.anular(TRF, dto, EMP, USER);
    expect(integracion.revertirDocumento).not.toHaveBeenCalled();
    expect(tx.tes_cuentas.update).toHaveBeenCalledTimes(2);
  });

  it('conciliada (D1): el chequeo previo ve una línea conciliada → 400 TRANSFERENCIA_CONCILIADA sin tocar nada', async () => {
    const { prisma, tx, integracion, servicio } = armar({ conciliadas: ['md-1'] });
    expect(await falla(servicio.anular(TRF, dto, EMP, USER))).toMatchObject({ status: 400, codigo: 'TRANSFERENCIA_CONCILIADA' });
    expect(prisma.tes_extracto_lineas.findFirst.mock.calls[0][0].where).toEqual({ movimiento_id: { in: ['mo-1', 'md-1'] }, conciliado: true });
    expect(prisma.$transaction).not.toHaveBeenCalled();
    expect(tx.tes_cuentas.update).not.toHaveBeenCalled();
    expect(integracion.revertirDocumento).not.toHaveBeenCalled();
  });

  it('conciliada entre medio: el updateMany cuenta 0 y la relectura en el tx la ve → 400 TRANSFERENCIA_CONCILIADA', async () => {
    const { tx, integracion, servicio } = armar({ updateMany: 0, conciliadaEnTx: true });
    expect(await falla(servicio.anular(TRF, dto, EMP, USER))).toMatchObject({ status: 400, codigo: 'TRANSFERENCIA_CONCILIADA' });
    expect(tx.tes_extracto_lineas.findFirst).toHaveBeenCalledTimes(1);
    expect(tx.tes_cuentas.update).not.toHaveBeenCalled();
    expect(integracion.revertirDocumento).not.toHaveBeenCalled();
  });

  it('la auditoría TES_TRANSFERENCIA_ANULADA va después del commit, con el motivo', async () => {
    const { prisma, audit, servicio } = armar();
    const orden: string[] = [];
    prisma.$transaction.mockImplementation(async (cb: any) => {
      const r = await cb(armar().tx);
      orden.push('commit');
      return r;
    });
    audit.log.mockImplementation(() => (orden.push('audit'), Promise.resolve()));
    await servicio.anular(TRF, dto, EMP, USER);
    expect(orden).toEqual(['commit', 'audit']);
    expect(audit.log).toHaveBeenCalledWith(expect.objectContaining({ action: 'TES_TRANSFERENCIA_ANULADA', entity_id: TRF, new_value: { motivo: 'Error de carga' } }));
  });
});

describe('id que no es UUID (F7)', () => {
  it('findOne, anular y reintentar → 404 TRANSFERENCIA_NO_ENCONTRADA sin consultar Prisma', async () => {
    const { prisma, servicio } = armar();
    expect(await falla(servicio.findOne('abc', EMP))).toMatchObject({ status: 404, codigo: 'TRANSFERENCIA_NO_ENCONTRADA' });
    expect(await falla(servicio.anular('abc', { motivo: 'x' }, EMP, USER))).toMatchObject({ status: 404, codigo: 'TRANSFERENCIA_NO_ENCONTRADA' });
    expect(await falla(servicio.reintentarContabilizacion(EMP, 'abc'))).toMatchObject({ status: 404, codigo: 'TRANSFERENCIA_NO_ENCONTRADA' });
    expect(prisma.tes_movimientos.findMany).not.toHaveBeenCalled();
  });
});
