import { crearIntegracionMock } from './__helpers__/integracion-mock';
import { resolverCuentaPagoGasto } from '../../common/utils/cuenta-pago-gasto.util';
import { montoEnMonedaDeCuenta } from '../../common/utils/moneda-cuenta.util';

// Task 9 (gastos en el kit): deducible por ítem (S12), redondeo a guaraníes (N2),
// el mismo resolvedor de cuenta de pago que Tesorería (N6), el resultado del asiento
// (N3) y el número de documento legible y único (N7).

const lineas = (s: any) => s.asientos.crearConfirmado.mock.calls[0][3].lineas;
const linea = (s: any, cuenta: string) => lineas(s).find((l: any) => l.cuenta_id === cuenta);
const haber = (s: any) => lineas(s).find((l: any) => l.haber_moneda > 0);
const suma = (s: any, campo: 'debe_moneda' | 'haber_moneda') =>
  lineas(s).reduce((a: number, l: any) => a + Number(l[campo] || 0), 0);

const tipo = (cuenta: string, deducible = true) => ({ cuenta_contable_id: cuenta, descripcion: cuenta, deducible });

const gasto = (over: any = {}) => ({
  id: 'g1',
  empresa_id: 'emp',
  sucursal_id: null,
  anulado: false,
  deducible: true,
  forma_pago: 'CONTADO',
  proveedor_id: null,
  medio_pago_id: null,
  cuenta_tesoreria_id: null,
  moneda_id: 'mon-pyg',
  pago_historico: false,
  numero_factura: '001-001-0000001',
  descripcion: 'Combustible camioneta',
  proveedores: null,
  moneda: { codigo: 'PYG' },
  cotizacion: null,
  fecha_emision: new Date('2026-10-05T00:00:00.000Z'),
  total: 3300,
  total_iva_10: 300,
  total_iva_5: 0,
  // Un ítem de un tipo deducible y otro de un tipo no deducible, los dos al 10 %.
  gasto_det: [
    { subtotal: 2200, monto_iva: 200, porcentaje_iva: 10, tipo_gasto: tipo('cta-COMBUSTIBLE') },
    { subtotal: 1100, monto_iva: 100, porcentaje_iva: 10, tipo_gasto: tipo('cta-REGALOS', false) },
  ],
  ...over,
});

const reglaPago = (medio: string | null, moneda: string | null, cuenta: string, activo = true) => ({
  medio_pago_id: medio,
  moneda_id: moneda,
  activo,
  cuenta_id: `tes-${cuenta}`,
  cuenta: {
    id: `tes-${cuenta}`,
    nombre: cuenta,
    moneda: 'PYG',
    cuenta_contable_id: `cta-${cuenta}`,
    activo: true,
    empresa_id: 'emp',
  },
});

const base = (g: any, extra: any = {}) => ({
  gasto_cab: { findUnique: jest.fn().mockResolvedValue(g) },
  config_compras: { findUnique: jest.fn().mockResolvedValue(null) },
  tes_reglas: { findMany: jest.fn().mockResolvedValue([]) },
  tes_cuentas: { findFirst: jest.fn().mockResolvedValue(null) },
  // Medios que no mueven caja (medio-pago-sin-caja.util): un medio común, sin marcar en la empresa.
  medio_pago: { findUnique: jest.fn().mockResolvedValue({ codigo: 1 }) },
  empresa_medio_pago: { findFirst: jest.fn().mockResolvedValue(null) },
  ...extra,
});

describe('deducible por ítem (S12)', () => {
  it('ítem no deducible en comprobante deducible: su IVA va a IVA_NO_DEDUCIBLE (CUENTA) y el IVA crédito solo lleva el de los otros', async () => {
    const s = crearIntegracionMock(base(gasto()));
    await s.integrarGasto('g1');
    expect(linea(s, 'cta-COMBUSTIBLE').debe_moneda).toBe(2000);
    expect(linea(s, 'cta-REGALOS').debe_moneda).toBe(1000);
    expect(linea(s, 'cta-IVA_CREDITO_10').debe_moneda).toBe(200);
    expect(linea(s, 'cta-IVA_NO_DEDUCIBLE')).toMatchObject({ debe_moneda: 100, mapeo_concepto: 'IVA_NO_DEDUCIBLE' });
    expect(haber(s).haber_moneda).toBe(3300);
  });

  it('con SUMAR_A_PRINCIPAL se suma al gasto del ítem', async () => {
    const s = crearIntegracionMock(base(gasto()), [], { IVA_NO_DEDUCIBLE: 'SUMAR_A_PRINCIPAL' });
    await s.integrarGasto('g1');
    expect(linea(s, 'cta-REGALOS').debe_moneda).toBe(1100);
    expect(linea(s, 'cta-COMBUSTIBLE').debe_moneda).toBe(2000);
    expect(linea(s, 'cta-IVA_CREDITO_10').debe_moneda).toBe(200);
    expect(linea(s, 'cta-IVA_NO_DEDUCIBLE')).toBeUndefined();
    expect(suma(s, 'debe_moneda')).toBe(suma(s, 'haber_moneda'));
  });

  it('sin mapeo de IVA_NO_DEDUCIBLE: sin asiento, constancia y el motivo real en el resultado (I7)', async () => {
    const s = crearIntegracionMock(base(gasto()), ['IVA_NO_DEDUCIBLE']);
    await expect(s.integrarGasto('g1')).resolves.toEqual({
      estado: 'SIN_ASIENTO',
      motivo: 'Sin asiento: falta mapear IVA_NO_DEDUCIBLE',
    });
    expect(s.asientos.crearConfirmado).not.toHaveBeenCalled();
    expect(s.avisosMapeo.registrarFaltaMapeo).toHaveBeenCalledWith(
      expect.objectContaining({ origenTipo: 'gasto_cab', origenId: 'g1', conceptos: ['IVA_NO_DEDUCIBLE'] }),
    );
  });

  it('todos los ítems deducibles: no pide IVA_NO_DEDUCIBLE (lo de hoy)', async () => {
    const g = gasto({ total: 2200, total_iva_10: 200, gasto_det: [gasto().gasto_det[0]] });
    const s = crearIntegracionMock(base(g), ['IVA_NO_DEDUCIBLE']);
    await expect(s.integrarGasto('g1')).resolves.toEqual({ estado: 'CONFIRMADO' });
    expect(linea(s, 'cta-IVA_CREDITO_10').debe_moneda).toBe(200);
  });

  it('IVA del 5 % de un ítem no deducible sale del IVA crédito 5 %', async () => {
    const g = gasto({
      total: 4250,
      total_iva_10: 100,
      total_iva_5: 150,
      gasto_det: [
        { subtotal: 1100, monto_iva: 100, porcentaje_iva: 10, tipo_gasto: tipo('cta-COMBUSTIBLE') },
        { subtotal: 2100, monto_iva: 100, porcentaje_iva: 5, tipo_gasto: tipo('cta-REGALOS', false) },
        { subtotal: 1050, monto_iva: 50, porcentaje_iva: 5, tipo_gasto: tipo('cta-COMBUSTIBLE') },
      ],
    });
    const s = crearIntegracionMock(base(g));
    await s.integrarGasto('g1');
    expect(linea(s, 'cta-IVA_CREDITO_10').debe_moneda).toBe(100);
    expect(linea(s, 'cta-IVA_CREDITO_5').debe_moneda).toBe(50);
    expect(linea(s, 'cta-IVA_NO_DEDUCIBLE').debe_moneda).toBe(100);
    expect(suma(s, 'debe_moneda')).toBe(suma(s, 'haber_moneda'));
  });
});

describe('redondeo a guaraníes (N2)', () => {
  const enUsd = (cotizacion: number) =>
    gasto({
      numero_factura: null,
      moneda_id: 'mon-usd',
      moneda: { codigo: 'USD' },
      cotizacion,
      total: 100.55,
      total_iva_10: 9.14,
      proveedor_id: 'p1',
      proveedores: { personas: { razon_social: 'Estación Central S.A.' } },
      gasto_det: [
        { subtotal: 60.33, monto_iva: 5.48, porcentaje_iva: 10, tipo_gasto: tipo('cta-COMBUSTIBLE') },
        { subtotal: 40.22, monto_iva: 3.66, porcentaje_iva: 10, tipo_gasto: tipo('cta-PEAJES') },
      ],
    });

  it('USD 100,55 a 7300 sin factura: líneas en PYG enteras y el asiento cuadra', async () => {
    const s = crearIntegracionMock(base(enUsd(7300)));
    await expect(s.integrarGasto('g1')).resolves.toEqual({ estado: 'CONFIRMADO' });
    for (const l of lineas(s)) {
      expect(Number.isInteger(l.debe_moneda)).toBe(true);
      expect(Number.isInteger(l.haber_moneda)).toBe(true);
    }
    expect(haber(s).haber_moneda).toBe(734015);
    expect(suma(s, 'debe_moneda')).toBe(suma(s, 'haber_moneda'));
    expect(s.prisma.cont_documentos.upsert.mock.calls[0][0].create.numero_documento).toBe(
      'GASTO 05/10/2026 · Estación Central S.A.',
    );
  });

  /** Lo que descuenta Tesorería de una cuenta en guaraníes: el haber tiene que ser exactamente esto. */
  const egreso = (total: number, tc: number) => {
    const p = montoEnMonedaDeCuenta({ total, monedaDocumento: 'USD', cotizacion: tc, monedaCuenta: 'PYG' });
    if (p.ok === false) throw new Error(p.mensaje);
    return p.monto;
  };
  /** Gasto en USD con un ítem exento por monto, cada uno en su cuenta. */
  const usdPorItems = (tc: number, montos: number[], over: any = {}) =>
    gasto({
      moneda_id: 'mon-usd',
      moneda: { codigo: 'USD' },
      cotizacion: tc,
      total_iva_10: 0,
      total_iva_5: 0,
      total: Math.round(montos.reduce((a, b) => a + b, 0) * 100) / 100,
      gasto_det: montos.map((m, i) => ({
        subtotal: m,
        monto_iva: 0,
        porcentaje_iva: 0,
        tipo_gasto: tipo(`cta-G${i}`),
      })),
      ...over,
    });

  it('con una cotización con decimales: líneas enteras y el haber es exactamente el egreso de Tesorería', async () => {
    const s = crearIntegracionMock(base(enUsd(7312.5)));
    await expect(s.integrarGasto('g1')).resolves.toEqual({ estado: 'CONFIRMADO' });
    for (const l of lineas(s)) expect(Number.isInteger(l.debe_moneda) && Number.isInteger(l.haber_moneda)).toBe(true);
    // 100,55 × 7312,5 = 735 271,875 → 735 272.
    expect(haber(s).haber_moneda).toBe(egreso(100.55, 7312.5));
    expect(haber(s).haber_moneda).toBe(735272);
    expect(suma(s, 'debe_moneda')).toBe(suma(s, 'haber_moneda'));
  });

  it('4 líneas de USD 0,04 a 7312,5: no queda en borrador; el residuo va a una línea de gasto y el haber es el egreso', async () => {
    const s = crearIntegracionMock(base(usdPorItems(7312.5, [0.04, 0.04, 0.04, 0.04])));
    await expect(s.integrarGasto('g1')).resolves.toEqual({ estado: 'CONFIRMADO' });
    // Cada línea: 0,04 × 7312,5 = 292,5 → 293 (4 × 293 = 1172); el egreso: 0,16 × 7312,5 = 1170.
    expect(haber(s).haber_moneda).toBe(egreso(0.16, 7312.5));
    expect(haber(s).haber_moneda).toBe(1170);
    expect(suma(s, 'debe_moneda')).toBe(1170);
    expect(
      lineas(s)
        .filter((l: any) => l.debe_moneda > 0)
        .map((l: any) => l.debe_moneda)
        .sort(),
    ).toEqual([291, 293, 293, 293]);
  });

  it('USD 8,04 a 7312,5 → 58793 en los dos lados (mismo redondeo que Tesorería)', async () => {
    const s = crearIntegracionMock(base(usdPorItems(7312.5, [8.04])));
    await s.integrarGasto('g1');
    expect(egreso(8.04, 7312.5)).toBe(58793);
    expect(haber(s).haber_moneda).toBe(58793);
    expect(linea(s, 'cta-G0').debe_moneda).toBe(58793);
  });

  it('el residuo nunca cae en el IVA crédito, aunque sea la línea más grande', async () => {
    // Tres ítems en cuentas distintas: el IVA 10 % total (0,30) supera a cada neto (0,10…).
    const det = [0.11, 0.11, 0.11].map((m, i) => ({
      subtotal: m + 0.1,
      monto_iva: 0.1,
      porcentaje_iva: 10,
      tipo_gasto: tipo(`cta-G${i}`),
    }));
    const g = usdPorItems(7312.5, [], { total: 0.63, total_iva_10: 0.3, gasto_det: det });
    const s = crearIntegracionMock(base(g));
    await expect(s.integrarGasto('g1')).resolves.toEqual({ estado: 'CONFIRMADO' });
    expect(linea(s, 'cta-IVA_CREDITO_10').debe_moneda).toBe(egreso(0.3, 7312.5));
    expect(haber(s).haber_moneda).toBe(egreso(0.63, 7312.5));
    expect(suma(s, 'debe_moneda')).toBe(suma(s, 'haber_moneda'));
  });

  it('simulación: varias líneas a 7284,13 nunca quedan en borrador y el haber siempre es el egreso', async () => {
    let semilla = 12345;
    const azar = () => (semilla = (semilla * 1103515245 + 12345) % 2 ** 31) / 2 ** 31;
    for (let caso = 0; caso < 300; caso++) {
      const montos = Array.from({ length: 2 + (caso % 7) }, () => Math.round(azar() * 5000) / 100 + 0.01);
      const s = crearIntegracionMock(base(usdPorItems(7284.13, montos)));
      await expect(s.integrarGasto('g1')).resolves.toEqual({ estado: 'CONFIRMADO' });
      const total = Math.round(montos.reduce((a, b) => a + b, 0) * 100) / 100;
      expect(haber(s).haber_moneda).toBe(egreso(total, 7284.13));
      expect(suma(s, 'debe_moneda')).toBe(suma(s, 'haber_moneda'));
    }
  });

  it('un desbalance real (los ítems no suman el total) sí queda en borrador', async () => {
    const s = crearIntegracionMock(base(usdPorItems(7312.5, [10, 5], { total: 16 })));
    await expect(s.integrarGasto('g1')).resolves.toEqual({
      estado: 'BORRADOR',
      motivo: expect.stringContaining('Asiento desbalanceado'),
    });
    expect(s.asientos.crearConfirmado).not.toHaveBeenCalled();
  });

  it('un desbalance real de 1 centavo en moneda extranjera queda en borrador (ítems 10 y 5,01 contra 15,00)', async () => {
    const s = crearIntegracionMock(base(usdPorItems(7300, [10, 5.01], { total: 15 })));
    await expect(s.integrarGasto('g1')).resolves.toEqual({
      estado: 'BORRADOR',
      motivo: 'Asiento desbalanceado (DEBE=15.01 / HABER=15 USD)',
    });
    expect(s.asientos.crearConfirmado).not.toHaveBeenCalled();
  });

  it('sin ninguna línea de debe donde cargar el residuo: borrador con el motivo, no haber contra debe 0', async () => {
    const g = gasto({ total: 1, total_iva_10: 0, gasto_det: [{ subtotal: 0, monto_iva: 0, porcentaje_iva: 10, tipo_gasto: tipo('cta-COMBUSTIBLE') }] });
    const s = crearIntegracionMock(base(g));
    await expect(s.integrarGasto('g1')).resolves.toEqual({
      estado: 'BORRADOR',
      motivo: expect.stringContaining('no hay líneas de debe'),
    });
    expect(s.asientos.crearConfirmado).not.toHaveBeenCalled();
  });

  it('en guaraníes la tolerancia de siempre: 1 Gs. de diferencia se absorbe y no deja borrador', async () => {
    const g = gasto({ total: 3301 });
    const s = crearIntegracionMock(base(g));
    await expect(s.integrarGasto('g1')).resolves.toEqual({ estado: 'CONFIRMADO' });
    expect(haber(s).haber_moneda).toBe(3301);
    expect(suma(s, 'debe_moneda')).toBe(3301);
  });
});

describe('cuenta de pago: el mismo resolvedor que Tesorería (N6)', () => {
  it('regla del medio inactiva: tesorería y asiento acreditan la misma cuenta (la general)', async () => {
    const reglas = [reglaPago('mp1', null, 'BANCO_MEDIO', false), reglaPago(null, null, 'CAJA_GRAL')];
    const p = base(gasto({ medio_pago_id: 'mp1' }), { tes_reglas: { findMany: jest.fn().mockResolvedValue(reglas) } });
    const s = crearIntegracionMock(p);
    await s.integrarGasto('g1');
    const tesoreria = await resolverCuentaPagoGasto(s.prisma, 'emp', { medioPagoId: 'mp1', monedaId: 'mon-pyg' });
    expect(tesoreria.cuenta?.id).toBe('tes-CAJA_GRAL');
    expect(haber(s)).toMatchObject({
      cuenta_id: tesoreria.cuenta?.cuenta_contable_id,
      mapeo_nivel: 'FICHA',
      mapeo_concepto: 'FICHA_CUENTA_TESORERIA',
    });
  });

  it('con una regla por moneda, el asiento usa la de la moneda del gasto (no otra cualquiera)', async () => {
    const reglas = [reglaPago(null, null, 'CAJA_PYG'), reglaPago(null, 'mon-usd', 'BANCO_USD')];
    const g = gasto({
      moneda_id: 'mon-usd',
      moneda: { codigo: 'USD' },
      cotizacion: 7300,
      total: 33,
      total_iva_10: 3,
      gasto_det: [{ subtotal: 33, monto_iva: 3, porcentaje_iva: 10, tipo_gasto: tipo('cta-COMBUSTIBLE') }],
    });
    const s = crearIntegracionMock(base(g, { tes_reglas: { findMany: jest.fn().mockResolvedValue(reglas) } }));
    await s.integrarGasto('g1');
    expect(haber(s).cuenta_id).toBe('cta-BANCO_USD');
  });

  it('TRANSFERENCIA vieja ≡ CONTADO: sin regla ni medio mapeado va a CAJA_GENERAL, no a BANCOS_DEFAULT', async () => {
    const s = crearIntegracionMock(base(gasto({ forma_pago: 'TRANSFERENCIA', medio_pago_id: 'mp-transf' })));
    await s.integrarGasto('g1');
    expect(haber(s)).toMatchObject({ cuenta_id: 'cta-CAJA_GENERAL', mapeo_concepto: 'CAJA_GENERAL' });
  });

  it('TRANSFERENCIA vieja con el medio mapeado: la cuenta del medio', async () => {
    const s = crearIntegracionMock(base(gasto({ forma_pago: 'TRANSFERENCIA', medio_pago_id: 'mp-transf' })));
    s.mediosPago.resolverPorMedio.mockResolvedValue(new Map([['mp-transf', 'cta-BANCO']]));
    await s.integrarGasto('g1');
    expect(haber(s)).toMatchObject({ cuenta_id: 'cta-BANCO', mapeo_nivel: 'MEDIO_PAGO' });
  });

  it('histórico: misma cadena sin medio (la regla general, aunque el medio tenga la suya)', async () => {
    const reglas = [reglaPago('mp1', null, 'BANCO_MEDIO'), reglaPago(null, null, 'CAJA_GRAL')];
    const s = crearIntegracionMock(
      base(gasto({ medio_pago_id: 'mp1', pago_historico: true }), {
        tes_reglas: { findMany: jest.fn().mockResolvedValue(reglas) },
      }),
    );
    s.mediosPago.resolverPorMedio.mockResolvedValue(new Map([['mp1', 'cta-DEL_MEDIO']]));
    await s.integrarGasto('g1');
    expect(haber(s).cuenta_id).toBe('cta-CAJA_GRAL');
  });

  it('histórico sin regla: CAJA_GENERAL, sin mirar el medio', async () => {
    const s = crearIntegracionMock(base(gasto({ medio_pago_id: 'mp1', pago_historico: true })));
    s.mediosPago.resolverPorMedio.mockResolvedValue(new Map([['mp1', 'cta-DEL_MEDIO']]));
    await s.integrarGasto('g1');
    expect(haber(s)).toMatchObject({ cuenta_id: 'cta-CAJA_GENERAL', mapeo_concepto: 'CAJA_GENERAL' });
  });
});

describe('resultado del asiento (N3)', () => {
  it("devuelve { estado: 'BORRADOR', motivo } sin período", async () => {
    const s = crearIntegracionMock(base(gasto()));
    s.periodos.resolverPeriodoPorFecha.mockRejectedValue(new Error('No hay período para 2026-10-05'));
    await expect(s.integrarGasto('g1')).resolves.toEqual({
      estado: 'BORRADOR',
      motivo: expect.stringContaining('No hay período abierto'),
    });
    expect(s.asientos.crearConfirmado).not.toHaveBeenCalled();
  });

  it('devuelve CONFIRMADO al cuadrar', async () => {
    const s = crearIntegracionMock(base(gasto()));
    await expect(s.integrarGasto('g1')).resolves.toEqual({ estado: 'CONFIRMADO' });
    expect(s.asientos.crearConfirmado).toHaveBeenCalledTimes(1);
  });

  it('ya contabilizado: CONFIRMADO sin rehacer nada', async () => {
    const s = crearIntegracionMock(base(gasto()));
    s.prisma.cont_documentos.findFirst.mockResolvedValue({ id: 'd', estado: 'CONFIRMADO', asiento: { id: 'a' } });
    await expect(s.integrarGasto('g1')).resolves.toEqual({ estado: 'CONFIRMADO' });
    expect(s.asientos.crearConfirmado).not.toHaveBeenCalled();
  });

  it('anulado: NO_CORRESPONDE (no se confunde con una falta de mapeo)', async () => {
    const s = crearIntegracionMock(base(gasto({ anulado: true })));
    await expect(s.integrarGasto('g1')).resolves.toEqual({ estado: 'NO_CORRESPONDE' });
  });

  it('sin el módulo de Contabilidad: SIN_MODULO y no toca nada', async () => {
    const s = crearIntegracionMock(base(gasto()));
    s.tieneModuloContabilidad.mockResolvedValue(false);
    await expect(s.integrarGasto('g1')).resolves.toEqual({ estado: 'SIN_MODULO' });
    expect(s.asientos.crearConfirmado).not.toHaveBeenCalled();
    expect(s.prisma.cont_documentos.upsert).not.toHaveBeenCalled();
  });
});

describe('número de documento (N7)', () => {
  const sinFactura = gasto({
    numero_factura: null,
    proveedor_id: 'p1',
    proveedores: { personas: { razon_social: 'Estación Central S.A.' } },
  });

  it('si otro gasto ya usa el número, agrega la descripción', async () => {
    const s = crearIntegracionMock(base(sinFactura));
    s.prisma.cont_documentos.findFirst.mockImplementation(async ({ where }: any) =>
      where.numero_documento === 'GASTO 05/10/2026 · Estación Central S.A.' ? { id: 'otro' } : null,
    );
    await s.integrarGasto('g1');
    const numero = s.prisma.cont_documentos.upsert.mock.calls[0][0].create.numero_documento;
    expect(numero).toBe('GASTO 05/10/2026 · Estación · Combustible camionet');
    expect(numero.endsWith(' · Combustible camionet')).toBe(true);
    expect(numero.length).toBeLessThanOrEqual(50);
    // Busca otro documento de la empresa con ese número y otro origen.
    expect(s.prisma.cont_documentos.findFirst).toHaveBeenCalledWith(
      expect.objectContaining({
        where: {
          empresa_id: 'emp',
          numero_documento: 'GASTO 05/10/2026 · Estación Central S.A.',
          origen_id: { not: 'g1' },
        },
      }),
    );
  });

  it('si el repetido es un egreso de Tesorería, el asiento también agrega la descripción (mismo texto en los dos)', async () => {
    const s = crearIntegracionMock(base(sinFactura));
    s.prisma.tes_movimientos.findFirst.mockResolvedValue({ id: 'mov-otro' });
    await s.integrarGasto('g1');
    expect(s.prisma.cont_documentos.upsert.mock.calls[0][0].create.numero_documento).toBe(
      'GASTO 05/10/2026 · Estación · Combustible camionet',
    );
  });

  it('con factura usa su número y no busca repetidos', async () => {
    const s = crearIntegracionMock(base(gasto()));
    await s.integrarGasto('g1');
    expect(s.prisma.cont_documentos.upsert.mock.calls[0][0].create.numero_documento).toBe('001-001-0000001');
    // Ninguna búsqueda de repetidos por número (las otras son el documento propio y el lock de M11).
    const porNumero = s.prisma.cont_documentos.findFirst.mock.calls.filter(([a]: any) => a.where.numero_documento);
    expect(porNumero).toHaveLength(0);
  });
});

describe('revisión de buenas prácticas (I4, I7, I13, M10)', () => {
  it('I7: si la constancia de la falta de mapeo no se pudo registrar, el motivo igual llega', async () => {
    const s = crearIntegracionMock(base(gasto()), ['IVA_NO_DEDUCIBLE']);
    s.avisosMapeo.registrarFaltaMapeo.mockRejectedValue(new Error('audit_logs no responde'));
    await expect(s.integrarGasto('g1')).resolves.toEqual({
      estado: 'SIN_ASIENTO',
      motivo: 'Sin asiento: falta mapear IVA_NO_DEDUCIBLE',
    });
  });

  it('I4: el asiento rehecho lo firma el usuario que se le pasa (quien edita), no el autor', async () => {
    const s = crearIntegracionMock(base(gasto({ usuario_id: 'u-autor' })));
    await s.integrarGasto('g1', { usuarioId: 'u-edita' });
    expect(s.asientos.crearConfirmado.mock.calls[0][1]).toBe('u-edita');
  });

  it('I4: sin usuario explícito (alta), firma quien cargó el gasto', async () => {
    const s = crearIntegracionMock(base(gasto({ usuario_id: 'u-autor' })));
    await s.integrarGasto('g1');
    expect(s.asientos.crearConfirmado.mock.calls[0][1]).toBe('u-autor');
  });

  it('M10: con la referencia ya decidida la usa tal cual (no la vuelve a calcular)', async () => {
    const s = crearIntegracionMock(base(gasto({ numero_factura: null })));
    await s.integrarGasto('g1', { referencia: 'GASTO 05/10/2026 · Ya decidida' });
    expect(s.prisma.cont_documentos.upsert.mock.calls[0][0].create.numero_documento).toBe('GASTO 05/10/2026 · Ya decidida');
    expect(s.prisma.tes_movimientos.findFirst).not.toHaveBeenCalled();
  });

  it('I13: la cuenta elegida ya no sirve → BORRADOR con el motivo, sin acreditar otra cuenta', async () => {
    const s = crearIntegracionMock(base(gasto({ cuenta_tesoreria_id: 'tes-vieja', medio_pago_id: 'mp1' })));
    s.mediosPago.resolverPorMedio.mockResolvedValue(new Map([['mp1', 'cta-DEL_MEDIO']]));
    const r = await s.integrarGasto('g1');
    expect(r).toEqual({ estado: 'BORRADOR', motivo: expect.stringContaining('La cuenta elegida en el gasto no está activa o no es de la empresa') });
    expect(s.asientos.crearConfirmado).not.toHaveBeenCalled();
  });

  // M11: dos reintentos a la vez no chocan en cont_documentos (P2002 → "no se pudo contabilizar").
  it('M11: bloquea la fila del gasto en la transacción del asiento y, si otro ya lo confirmó, no crea otro', async () => {
    const s = crearIntegracionMock(base(gasto()));
    s.prisma.cont_documentos.findFirst.mockImplementation(async ({ where }: any) =>
      where.estado === 'CONFIRMADO' ? { id: 'd-del-otro' } : null,
    );
    await expect(s.integrarGasto('g1')).resolves.toEqual({ estado: 'CONFIRMADO' });
    expect(String(s.prisma.$queryRaw.mock.calls[0][0].join('?'))).toContain('FOR UPDATE');
    expect(s.asientos.crearConfirmado).not.toHaveBeenCalled();
    expect(s.prisma.cont_documentos.upsert).not.toHaveBeenCalled();
  });
});


describe('contado diferido a la orden de pago (I1: por lo que el gasto es, no por la config)', () => {
  const vinculos = (opDets: any[] = []) => ({
    orden_pago_proveedor_det: { findMany: jest.fn().mockResolvedValue(opDets) },
    pagos_proveedor: { findMany: jest.fn().mockResolvedValue([]) },
    rec_multi_gastos: { findMany: jest.fn().mockResolvedValue([]) },
  });
  const tipoDoc = (s: any) => s.prisma.cont_documentos.upsert.mock.calls[0][0].create.tipo;
  // La config ya no se lee para decidir: aunque diga «incluir contado en OP», manda el gasto.
  const configEncendida = { config_compras: { findUnique: jest.fn().mockResolvedValue({ incluir_contado_en_orden_pago: true }) } };

  it('histórico importado con la opción encendida: haber en Caja (la regla/CAJA_GENERAL), documento GASTO_CONTADO', async () => {
    const g = gasto({ proveedor_id: 'prov1', estado: 'pagada', pago_historico: true });
    const s = crearIntegracionMock(base(g, { ...configEncendida, ...vinculos() }));
    await s.integrarGasto('g1');
    expect(haber(s)).toMatchObject({ cuenta_id: 'cta-CAJA_GENERAL', mapeo_concepto: 'CAJA_GENERAL' });
    expect(tipoDoc(s)).toBe('GASTO_CONTADO');
  });

  it('contado pendiente (registrado) con proveedor: es el diferido a OP, acredita PROVEEDORES', async () => {
    const g = gasto({ proveedor_id: 'prov1', estado: 'registrado' });
    const s = crearIntegracionMock(base(g, vinculos()));
    await s.integrarGasto('g1');
    expect(haber(s).mapeo_concepto).toBe('PROVEEDORES');
    expect(tipoDoc(s)).toBe('GASTO_CREDITO');
  });

  it('contado pagado por una OP: sigue en PROVEEDORES al rehacer el asiento', async () => {
    const g = gasto({ proveedor_id: 'prov1', estado: 'pagada' });
    const s = crearIntegracionMock(base(g, vinculos([{ cuentas_pagar: { origen_id: 'g1' } }])));
    await s.integrarGasto('g1');
    expect(haber(s).mapeo_concepto).toBe('PROVEEDORES');
  });

  it('contado pagado en el momento y la opción encendida después: rehacer no lo pasa a PROVEEDORES', async () => {
    const g = gasto({ proveedor_id: 'prov1', estado: 'pagada' });
    const s = crearIntegracionMock(base(g, { ...configEncendida, ...vinculos() }));
    await s.integrarGasto('g1');
    expect(haber(s)).toMatchObject({ cuenta_id: 'cta-CAJA_GENERAL', mapeo_concepto: 'CAJA_GENERAL' });
    expect(tipoDoc(s)).toBe('GASTO_CONTADO');
  });
});
