import { crearIntegracionMock } from './__helpers__/integracion-mock';

// A6: integrarMovimientoTesoreria devuelve por qué no hay asiento (antes: `return;` mudo).
const mov = (o: Record<string, unknown> = {}, cuenta: Record<string, unknown> = {}, det: Record<string, unknown> = {}) => ({
  id: 'm1',
  empresa_id: 'emp',
  tipo: 'EGRESO',
  fecha: new Date('2026-10-13'),
  descripcion: 'Pago',
  origen_tipo: null,
  referencia: null,
  created_by: 'u1',
  embarque_id: null,
  tipo_pago_importacion: null,
  cuenta_id: 'tes1',
  cuenta: { cuenta_contable_id: 'cta-banco', moneda: 'PYG', ...cuenta },
  detalles: [{ categoria_id: 'cat', monto: 100, cuenta_contable_id: null, concepto_contable: null, categoria: { nombre: 'Otro Egreso', cuenta_contable_id: 'cta-cat' }, ...det }],
  ...o,
});
const integrador = (m: unknown, faltan: string[] = []) =>
  crearIntegracionMock({ tes_movimientos: { findUnique: jest.fn().mockResolvedValue(m) }, tes_categoria_cuenta_contable: { findMany: jest.fn().mockResolvedValue([]) } }, faltan);

describe('integrarMovimientoTesoreria — resultado (A6)', () => {
  it('crea el asiento → { generado: true }', async () => {
    expect(await integrador(mov()).integrarMovimientoTesoreria('m1')).toEqual({ generado: true });
  });
  it('movimiento inexistente → 404 (no es POR_ORIGEN, M3)', async () => {
    await expect(integrador(null).integrarMovimientoTesoreria('m1')).rejects.toMatchObject({ status: 404, response: { codigo: 'MOVIMIENTO_NO_ENCONTRADO' } });
  });
  it('con asiento propio por su origen → POR_ORIGEN', async () => {
    expect(await integrador(mov({ origen_tipo: 'gasto_cab' })).integrarMovimientoTesoreria('m1')).toEqual({ generado: false, motivo: 'POR_ORIGEN' });
  });
  it('sin el módulo → SIN_MODULO', async () => {
    const s = integrador(mov());
    s.tieneModuloContabilidad.mockResolvedValue(false);
    expect(await s.integrarMovimientoTesoreria('m1')).toEqual({ generado: false, motivo: 'SIN_MODULO' });
  });
  it('ya tiene documento → { generado: true }', async () => {
    const s = integrador(mov());
    s.prisma.cont_documentos.findFirst.mockResolvedValue({ id: 'doc' });
    expect(await s.integrarMovimientoTesoreria('m1')).toEqual({ generado: true });
    expect(s.asientos.crearConfirmado).not.toHaveBeenCalled();
  });
  it('la cuenta de tesorería sin cuenta contable → CUENTA_SIN_CUENTA_CONTABLE', async () => {
    expect(await integrador(mov({}, { cuenta_contable_id: null })).integrarMovimientoTesoreria('m1')).toEqual({ generado: false, motivo: 'CUENTA_SIN_CUENTA_CONTABLE' });
  });
  it('categoría sin cuenta ni mapeo → CATEGORIA_SIN_CUENTA con su nombre', async () => {
    const s = integrador(mov({}, {}, { categoria: { nombre: 'Otro Egreso', cuenta_contable_id: null } }));
    expect(await s.integrarMovimientoTesoreria('m1')).toEqual({ generado: false, motivo: 'CATEGORIA_SIN_CUENTA', categoria: 'Otro Egreso' });
    expect(s.asientos.crearConfirmado).not.toHaveBeenCalled();
  });
  it('sin período abierto → SIN_PERIODO_ABIERTO', async () => {
    const s = integrador(mov());
    s.periodos.resolverPeriodoPorFecha.mockRejectedValue(new Error('No hay período'));
    expect(await s.integrarMovimientoTesoreria('m1')).toEqual({ generado: false, motivo: 'SIN_PERIODO_ABIERTO' });
  });
  it('concepto sin mapear → undefined (lo atrapa conAvisoDeMapeo) y deja la constancia', async () => {
    const s = integrador(mov({}, {}, { concepto_contable: 'SUELDOS_A_PAGAR' }), ['SUELDOS_A_PAGAR']);
    expect(await s.integrarMovimientoTesoreria('m1')).toBeUndefined();
    expect(s.avisosMapeo.registrarFaltaMapeo).toHaveBeenCalledTimes(1);
  });
});
