import { TesReportesService } from './tes-reportes.service';

/**
 * Reporte "Extracto de Cuenta" (Tesorería → Reportes) con transferencias entre cuentas
 * propias. Caso DOBA 21/10: compra de USD 24.000 a 5.750 → sale Gs. 138.000.000 de la
 * cuenta en guaraníes y entran USD 24.000 a la cuenta en dólares. Antes las dos puntas
 * salían sin monto en Ingreso/Egreso y el saldo las restaba en las dos cuentas.
 */
const CUENTA = { id: 'cta', nombre: 'Cuenta', tipo: 'BANCO', moneda: 'USD', saldo_inicial: 1000, banco_id: null };

const crear = (periodo: any[], previos: any[]) => {
  const prisma: any = {
    tes_cuentas: { findFirst: jest.fn().mockResolvedValue(CUENTA) },
    bancos: { findFirst: jest.fn() },
    tes_movimientos: {
      findMany: jest.fn().mockImplementation(async ({ where }: any) => (where.fecha.lt && !where.fecha.gte ? previos : periodo)),
    },
  };
  return new TesReportesService(prisma, {} as any);
};

const filtros = { cuenta_id: 'cta', fecha_desde: '2026-10-01', fecha_hasta: '2026-10-31' };

describe('TesReportesService.extractoCuenta con transferencias', () => {
  it('la punta destino entra como ingreso y suma al saldo', async () => {
    const s = crear([{ fecha: new Date('2026-10-21'), tipo: 'TRANSFERENCIA', origen_tipo: 'TRANSFERENCIA_DESTINO', monto: 24000, descripcion: 'Compra de 24.000 x 5750' }], []);

    const r = await s.extractoCuenta('emp', filtros);

    expect(r.lineas[0]).toMatchObject({ ingreso: 24000, egreso: 0, saldo: 25000 });
    expect(r.saldoFinal).toBe(25000);
  });

  it('la punta origen sale como egreso', async () => {
    const s = crear([{ fecha: new Date('2026-10-21'), tipo: 'TRANSFERENCIA', origen_tipo: 'TRANSFERENCIA_ORIGEN', monto: 400, descripcion: 'Compra' }], []);

    const r = await s.extractoCuenta('emp', filtros);

    expect(r.lineas[0]).toMatchObject({ ingreso: 0, egreso: 400, saldo: 600 });
  });

  it('el saldo anterior cuenta las transferencias recibidas antes del período', async () => {
    const s = crear(
      [],
      [
        { tipo: 'TRANSFERENCIA', origen_tipo: 'TRANSFERENCIA_DESTINO', monto: 500 },
        { tipo: 'EGRESO', origen_tipo: null, monto: 200 },
        { tipo: 'INGRESO', origen_tipo: null, monto: 100 },
      ],
    );

    const r = await s.extractoCuenta('emp', filtros);

    expect(r.saldoAnterior).toBe(1400);
  });
});
