import { TesMovimientosService } from './tes-movimientos.service';
import { deltaMovimiento, sentidoMovimiento } from './sentido-movimiento';

describe('sentidoMovimiento', () => {
  it('ingresos y egresos por tipo', () => {
    expect(sentidoMovimiento({ tipo: 'INGRESO' })).toBe('INGRESO');
    expect(sentidoMovimiento({ tipo: 'EGRESO' })).toBe('EGRESO');
  });

  it('una transferencia sale de la cuenta origen y entra en la destino', () => {
    expect(sentidoMovimiento({ tipo: 'TRANSFERENCIA', origen_tipo: 'TRANSFERENCIA_ORIGEN' })).toBe('EGRESO');
    expect(sentidoMovimiento({ tipo: 'TRANSFERENCIA', origen_tipo: 'TRANSFERENCIA_DESTINO' })).toBe('INGRESO');
    expect(deltaMovimiento({ tipo: 'TRANSFERENCIA', origen_tipo: 'TRANSFERENCIA_DESTINO', monto: '3500' })).toBe(3500);
  });
});

describe('TesMovimientosService.getExtracto — libro banco con transferencias (DOBA, mayo 2026)', () => {
  const crear = (cuentaId: string, movimientos: any[], anteriores: any[] = []) => {
    const prisma: any = {
      tes_cuentas: { findFirst: jest.fn().mockResolvedValue({ id: cuentaId, nombre: 'x', tipo: 'BANCO_CC', moneda: 'PYG', saldo_inicial: 0 }) },
      tes_movimientos: {
        findMany: jest.fn().mockImplementation(({ where }) => (where.fecha?.lt ? anteriores : movimientos)),
      },
    };
    return new TesMovimientosService(prisma, {} as any);
  };

  it('la venta de dólares sale como egreso de la cuenta en guaraníes', async () => {
    const s = crear('pyg', [
      { tipo: 'INGRESO', origen_tipo: null, monto: 30000000 },
      { tipo: 'TRANSFERENCIA', origen_tipo: 'TRANSFERENCIA_ORIGEN', monto: 21140000 },
    ]);
    const r = await s.getExtracto('emp', 'pyg', '2026-05-01', '2026-05-31');
    expect(r.movimientos.map((m: any) => m.sentido)).toEqual(['INGRESO', 'EGRESO']);
    expect(r.saldo_cierre).toBe(8860000);
  });

  it('en la cuenta en dólares la transferencia suma, también en el saldo de apertura', async () => {
    const s = crear(
      'usd',
      [{ tipo: 'TRANSFERENCIA', origen_tipo: 'TRANSFERENCIA_DESTINO', monto: 3500 }],
      [{ tipo: 'TRANSFERENCIA', origen_tipo: 'TRANSFERENCIA_DESTINO', monto: 1000 }],
    );
    const r = await s.getExtracto('emp', 'usd', '2026-05-01', '2026-05-31');
    expect(r.saldo_apertura).toBe(1000);
    expect(r.movimientos[0].sentido).toBe('INGRESO');
    expect(r.saldo_cierre).toBe(4500);
  });
});
