import { Logger } from '@nestjs/common';
import { GastosTesoreriaService, tieneMovimientoConciliado } from './gastos-tesoreria.service';

/**
 * Reversión del egreso de un gasto (C1, I1, I6 y M3 de la revisión de buenas prácticas):
 * corre en la transacción del llamador, un error siempre llega al llamador (no hay
 * opción para tragarlo), cada movimiento se toma con una condición de estado (dos
 * anulaciones a la vez no devuelven el saldo dos veces) y el motivo es el real.
 */
beforeAll(() => {
  jest.spyOn(Logger.prototype, 'warn').mockImplementation(() => undefined);
  jest.spyOn(Logger.prototype, 'error').mockImplementation(() => undefined);
});

function armar(movimientos: { id: string; cuenta_id: string; monto: number }[], tomados: number[] = movimientos.map(() => 1)) {
  let llamada = 0;
  const tx: any = {
    $queryRaw: jest.fn().mockResolvedValue([]),
    tes_cheques: { findMany: jest.fn().mockResolvedValue([{ id: 'ch1' }]), updateMany: jest.fn().mockResolvedValue({ count: 1 }) },
    tes_movimientos: {
      findMany: jest.fn().mockResolvedValue(movimientos),
      updateMany: jest.fn().mockImplementation(() => ({ count: tomados[llamada++] ?? 0 })),
    },
    tes_cuentas: { update: jest.fn().mockResolvedValue({}) },
  };
  const prisma: any = { $transaction: jest.fn((fn: any) => fn(tx)) };
  return { service: new GastosTesoreriaService(prisma), tx, prisma };
}

describe('GastosTesoreriaService.revertirGasto(tx, …)', () => {
  it('usa la transacción del llamador y no abre otra', async () => {
    const { service, tx, prisma } = armar([{ id: 'm1', cuenta_id: 'c1', monto: 100 }]);
    await service.revertirGasto(tx, 'g1', 'emp', 'Cargado dos veces');
    expect(prisma.$transaction).not.toHaveBeenCalled();
    expect(tx.$queryRaw).toHaveBeenCalledTimes(1);
  });

  it('un error de la base llega al llamador (no se loguea y se sigue)', async () => {
    const { service, tx } = armar([]);
    tx.tes_movimientos.findMany.mockRejectedValue(new Error('value too long for type character varying(500)'));
    await expect(service.revertirGasto(tx, 'g1', 'emp', 'x')).rejects.toThrow('value too long');
  });

  it('el motivo llega tal cual al cheque y al movimiento', async () => {
    const { service, tx } = armar([{ id: 'm1', cuenta_id: 'c1', monto: 100 }]);
    await service.revertirGasto(tx, 'g1', 'emp', 'Cargado dos veces');
    expect(tx.tes_cheques.updateMany).toHaveBeenCalledWith(
      expect.objectContaining({ data: expect.objectContaining({ motivo: 'Cargado dos veces' }) }),
    );
    expect(tx.tes_movimientos.updateMany).toHaveBeenCalledWith(
      expect.objectContaining({ data: expect.objectContaining({ motivo_anulacion: 'Cargado dos veces' }) }),
    );
  });

  it('cada movimiento se toma condicionado a CONFIRMADO y el saldo vuelve solo si se tomó', async () => {
    const { service, tx } = armar(
      [
        { id: 'm1', cuenta_id: 'c1', monto: 100 },
        { id: 'm2', cuenta_id: 'c2', monto: 50 },
      ],
      [1, 0],
    );
    await service.revertirGasto(tx, 'g1', 'emp', 'x');
    expect(tx.tes_movimientos.updateMany).toHaveBeenCalledWith(
      expect.objectContaining({ where: { id: 'm1', estado: 'CONFIRMADO' } }),
    );
    expect(tx.tes_cuentas.update).toHaveBeenCalledTimes(1);
    expect(tx.tes_cuentas.update).toHaveBeenCalledWith({ where: { id: 'c1' }, data: { saldo_actual: { increment: 100 } } });
  });
});

describe('tieneMovimientoConciliado (F8: parametrizado por origen, lo usan Gastos y la OP)', () => {
  const db = (conciliada: boolean) => ({
    tes_extracto_lineas: { findFirst: jest.fn().mockResolvedValue(conciliada ? { id: 'ext-1' } : null) },
  });

  it('la función exportada busca el egreso CONFIRMADO conciliado del origen que se le pasa', async () => {
    const d = db(true);
    await expect(tieneMovimientoConciliado(d as any, 'emp', { origenTipo: 'ORDEN_PAGO_PROVEEDOR', origenId: 'op-1' })).resolves.toBe(true);
    expect(d.tes_extracto_lineas.findFirst).toHaveBeenCalledWith({
      where: {
        conciliado: true,
        movimiento: { empresa_id: 'emp', origen_tipo: 'ORDEN_PAGO_PROVEEDOR', origen_id: 'op-1', estado: 'CONFIRMADO' },
      },
      select: { id: true },
    });
    await expect(tieneMovimientoConciliado(db(false) as any, 'emp', { origenTipo: 'x', origenId: 'y' })).resolves.toBe(false);
  });

  it('el método del servicio de Gastos sigue igual: origen gasto_cab y el id del gasto', async () => {
    const d = db(true);
    const service = new GastosTesoreriaService({} as any);
    await expect(service.tieneMovimientoConciliado('g1', 'emp', d as any)).resolves.toBe(true);
    expect(d.tes_extracto_lineas.findFirst.mock.calls[0][0].where.movimiento).toEqual({
      empresa_id: 'emp',
      origen_tipo: 'gasto_cab',
      origen_id: 'g1',
      estado: 'CONFIRMADO',
    });
  });
});
