import { decidirPrecarga, mapeosInutilizables, noReproducibles } from './precarga-mapeo-sin-decisiones';

const m = (o: Record<string, string>) => new Map(Object.entries(o).map(([k, v]) => [k, { cuentaId: v, modo: 'CUENTA' }]));
const sinCategorias = { cuentaCategoria: { ANTICIPO: null, PAGO_SUELDOS: null, PAGO_IPS: null, PAGO_FINIQUITO: null } };

it('reproduce lo que hace hoy el código, sin pisar lo mapeado', () => {
  const r = decidirPrecarga(m({ CAJA_GENERAL: 'caja', INVENTARIO: 'inv', IMPORTACIONES_EN_CURSO: 'puente', PROVEEDORES: 'prov', CHEQUES_EN_CARTERA: 'cart', RETENCION_RENTA_FAVOR: 'ire', ANTICIPO_PERSONAL: 'antp' }), sinCategorias);
  const de = (c: string) => r.find((x) => x.concepto === c);
  expect(de('CHEQUES_EN_CARTERA')).toBeUndefined(); // ya mapeado
  expect(de('CHEQUES_EN_TRANSITO')).toEqual({ concepto: 'CHEQUES_EN_TRANSITO', cuentaId: 'cart', modo: 'CUENTA' });
  // No reproducible con una cuenta (antes: la de tesorería del detalle o Caja): no se precarga.
  expect(de('CHEQUES_A_PAGAR')).toBeUndefined();
  expect(de('PAGO_COMISIONES_FONDOS')?.cuentaId).toBe('caja');
  expect(de('PROVEEDORES_EXTERIOR')?.cuentaId).toBe('prov');
  expect(de('ACREEDORES_VARIOS')?.cuentaId).toBe('prov');
  expect(de('IMPORTACION_COMPRA')?.cuentaId).toBe('inv');
  expect(de('IMPORTACION_GASTO')).toEqual({ concepto: 'IMPORTACION_GASTO', cuentaId: null, modo: 'SUMAR_A_PRINCIPAL' });
  expect(de('IMPORTACION_PAGO_PROVEEDOR')?.cuentaId).toBe('puente');
  expect(de('IMPORTACION_TRIBUTOS')?.cuentaId).toBe('puente');
  expect(de('IMPORTACION_ANTICIPO_IRE')?.cuentaId).toBe('ire');
  expect(de('IVA_NO_DEDUCIBLE')?.modo).toBe('SUMAR_A_PRINCIPAL');
  expect(de('ANTICIPO_VIATICO')?.cuentaId).toBe('antp');
  expect(de('ANTICIPO_DESPACHO')).toBeUndefined();
});

it('sin cuenta puente, tributos e IRE van a inventario y no se precarga el pago al proveedor', () => {
  const r = decidirPrecarga(m({ CAJA_GENERAL: 'caja', INVENTARIO: 'inv' }), sinCategorias);
  const de = (c: string) => r.find((x) => x.concepto === c);
  expect(de('IMPORTACION_TRIBUTOS')?.cuentaId).toBe('inv');
  expect(de('IMPORTACION_ANTICIPO_IRE')?.cuentaId).toBe('inv');
  expect(de('IMPORTACION_PAGO_PROVEEDOR')).toBeUndefined();
});

it('es idempotente: con todo precargado no propone nada', () => {
  const primera = decidirPrecarga(m({ CAJA_GENERAL: 'caja', INVENTARIO: 'inv', PROVEEDORES: 'prov' }), sinCategorias);
  const todo = new Map([...m({ CAJA_GENERAL: 'caja', INVENTARIO: 'inv', PROVEEDORES: 'prov' }), ...primera.map((p) => [p.concepto, { cuentaId: p.cuentaId, modo: p.modo }] as const)]);
  expect(decidirPrecarga(todo, sinCategorias)).toEqual([]);
});

it('los movimientos de RRHH reproducen la cuenta de su categoría de tesorería', () => {
  const r = decidirPrecarga(m({ CAJA_GENERAL: 'caja' }), {
    cuentaCategoria: { ANTICIPO: 'cat-ant', PAGO_SUELDOS: 'cat-sue', PAGO_IPS: 'cat-ips', PAGO_FINIQUITO: 'cat-fin' },
  });
  const de = (c: string) => r.find((x) => x.concepto === c);
  expect(de('DESCUENTOS_VARIOS_RRHH')?.cuentaId).toBe('cat-ant'); // sin ANTICIPO_PERSONAL
  expect(de('SUELDOS_A_PAGAR')?.cuentaId).toBe('cat-sue');
  expect(de('IPS_A_DEPOSITAR')?.cuentaId).toBe('cat-ips');
  for (const c of ['INDEMNIZACION', 'PREAVISO', 'VACACIONES_FINIQUITO', 'AGUINALDO_FINIQUITO']) {
    expect(de(c)?.cuentaId).toBe('cat-fin');
  }
  // SUELDOS_JORNALES también es el gasto de la liquidación de sueldos: no se decide con el finiquito.
  expect(de('SUELDOS_JORNALES')).toBeUndefined();
  // Con ANTICIPO_PERSONAL mapeado manda ese, como el bucle del anticipo.
  const conAnticipo = decidirPrecarga(m({ ANTICIPO_PERSONAL: 'antp' }), { cuentaCategoria: { ANTICIPO: 'cat-ant' } });
  expect(conAnticipo.find((x) => x.concepto === 'DESCUENTOS_VARIOS_RRHH')?.cuentaId).toBe('antp');
});

it('no precarga lo que antes no generaba asiento', () => {
  const r = decidirPrecarga(m({ CAJA_GENERAL: 'caja', INVENTARIO: 'inv' }), sinCategorias);
  const conceptos = r.map((x) => x.concepto);
  // Viáticos: sin BANCO el asiento se omitía (el `?? CAJA_GENERAL` nunca corría).
  expect(conceptos).not.toContain('BANCO');
  expect(conceptos).not.toContain('REINTEGRO_EMPLEADO_PENDIENTE');
  expect(conceptos).not.toContain('DIFERENCIA_CAMBIO_GANADA');
  expect(conceptos).not.toContain('DIFERENCIA_CAMBIO_PERDIDA');
  // Sin cuenta de referencia no se inserta nada (queda sin mapear y avisa).
  expect(conceptos).not.toContain('PROVEEDORES_EXTERIOR');
  expect(conceptos).not.toContain('SUELDOS_A_PAGAR');
  // Respeta el CHECK de la tabla: CUENTA con cuenta, SUMAR sin cuenta.
  for (const p of r) expect(p.modo === 'CUENTA' ? !!p.cuentaId : p.cuentaId === null).toBe(true);
});

it('los IMPORTACION_* solo se precargan si la empresa usa importaciones', () => {
  const r = decidirPrecarga(m({ CAJA_GENERAL: 'caja', INVENTARIO: 'inv', IMPORTACIONES_EN_CURSO: 'puente' }), { ...sinCategorias, usaImportaciones: false });
  expect(r.filter((x) => x.concepto.startsWith('IMPORTACION_'))).toEqual([]);
  expect(r.find((x) => x.concepto === 'IVA_NO_DEDUCIBLE')?.modo).toBe('SUMAR_A_PRINCIPAL');
});

describe('mapeos contra cuentas inutilizables (desactivadas o de agrupación)', () => {
  const muerta = (cuentaId: string) => ({ cuentaId, modo: 'CUENTA', usable: false });

  it('una referencia inutilizable cae como en HEAD: puente muerta → tributos a inventario', () => {
    const mapeados = new Map([...m({ CAJA_GENERAL: 'caja', INVENTARIO: 'inv' }), ['IMPORTACIONES_EN_CURSO', muerta('puente')], ['RETENCION_RENTA_FAVOR', muerta('ire')]]);
    const r = decidirPrecarga(mapeados, sinCategorias);
    const de = (c: string) => r.find((x) => x.concepto === c);
    expect(de('IMPORTACION_TRIBUTOS')?.cuentaId).toBe('inv');
    expect(de('IMPORTACION_ANTICIPO_IRE')?.cuentaId).toBe('inv'); // IRE al costo, como HEAD
    expect(de('IMPORTACION_PAGO_PROVEEDOR')).toBeUndefined();
  });

  it('un concepto de respaldo con cuenta muerta se informa y no se pisa', () => {
    const mapeados = new Map([...m({ CAJA_GENERAL: 'caja' }), ['CHEQUES_A_PAGAR', muerta('vieja')]]);
    const r = decidirPrecarga(mapeados, sinCategorias);
    expect(r.find((x) => x.concepto === 'CHEQUES_A_PAGAR')).toBeUndefined();
    expect(mapeosInutilizables(mapeados)).toEqual(['CHEQUES_A_PAGAR']);
    expect(mapeosInutilizables(m({ CAJA_GENERAL: 'caja' }))).toEqual([]);
  });
});

describe('CHEQUES_A_PAGAR no se precarga: el dry-run lo informa como no reproducible', () => {
  // Prisma mínimo: la consulta de OP con cheque devuelve 3; las demás, 0.
  const prisma = () => ({
    $queryRawUnsafe: jest.fn().mockImplementation((sql: string) =>
      Promise.resolve([{ n: /orden_pago_proveedor_cab/.test(sql) && /mp\.codigo = 2/.test(sql) ? BigInt(3) : BigInt(0) }]),
    ),
  });

  it('nunca se propone, aunque CAJA_GENERAL esté mapeada', () => {
    expect(decidirPrecarga(m({ CAJA_GENERAL: 'caja' }), sinCategorias).find((x) => x.concepto === 'CHEQUES_A_PAGAR')).toBeUndefined();
  });

  it('sin mapear: informa las OP con cheque ya asentadas', async () => {
    const mapeados = m({ CAJA_GENERAL: 'caja' });
    const p = prisma();
    const nr = await noReproducibles(p as any, 'emp', mapeados, decidirPrecarga(mapeados, sinCategorias));
    const cheques = nr.find((x) => x.concepto === 'CHEQUES_A_PAGAR');
    expect(cheques).toMatchObject({ concepto: 'CHEQUES_A_PAGAR', documentos: 3 });
    expect(cheques?.ahora).toMatch(/pendientes/);
  });

  it('mapeado a una cuenta inutilizable: también se informa (usable)', async () => {
    const mapeados = new Map<string, { cuentaId: string | null; modo: string; usable?: boolean }>([
      ...m({ CAJA_GENERAL: 'caja' }),
      ['CHEQUES_A_PAGAR', { cuentaId: 'vieja', modo: 'CUENTA', usable: false }],
    ]);
    const nr = await noReproducibles(prisma() as any, 'emp', mapeados, decidirPrecarga(mapeados, sinCategorias));
    expect(nr.find((x) => x.concepto === 'CHEQUES_A_PAGAR')?.documentos).toBe(3);
  });

  it('con un mapeo usable no se informa', async () => {
    const mapeados = m({ CAJA_GENERAL: 'caja', CHEQUES_A_PAGAR: 'chq' });
    const nr = await noReproducibles(prisma() as any, 'emp', mapeados, decidirPrecarga(mapeados, sinCategorias));
    expect(nr.find((x) => x.concepto === 'CHEQUES_A_PAGAR')).toBeUndefined();
  });
});
