/** @jest-environment node */
import axios from 'axios';
import { fetchFineractGlAccounts, fetchFineractGlAccountsByCodes } from './omnl-ipsas-gl';

jest.mock('axios');
const mockedAxios = axios as jest.Mocked<typeof axios>;

describe('fetchFineractGlAccounts', () => {
  beforeEach(() => {
    process.env.OMNL_FINERACT_BASE_URL = 'https://example.test/fineract-provider/api/v1';
    process.env.OMNL_FINERACT_PASSWORD = 'secret';
    process.env.OMNL_FINERACT_USER = 'app.omnl';
    mockedAxios.get.mockReset();
  });

  it('stops after first page when Hybx returns top-level array (> limit)', async () => {
    const rows = Array.from({ length: 262 }, (_, i) => ({ id: i + 1, glCode: String(1000 + i) }));
    mockedAxios.get.mockResolvedValueOnce({ data: rows });
    const out = await fetchFineractGlAccounts();
    expect(out).toHaveLength(262);
    expect(mockedAxios.get).toHaveBeenCalledTimes(1);
  });
});

describe('fetchFineractGlAccountsByCodes', () => {
  beforeEach(() => {
    process.env.OMNL_FINERACT_BASE_URL = 'https://example.test/fineract-provider/api/v1';
    process.env.OMNL_FINERACT_PASSWORD = 'secret';
    mockedAxios.get.mockReset();
  });

  it('fetches each GL code separately', async () => {
    mockedAxios.get
      .mockResolvedValueOnce({ data: [{ id: 1, glCode: '1000', name: 'Reserve' }] })
      .mockResolvedValueOnce({ data: [{ id: 14, glCode: '13010', name: 'Nostro' }] });
    const out = await fetchFineractGlAccountsByCodes(['1000', '13010']);
    expect(out).toHaveLength(2);
    expect(mockedAxios.get).toHaveBeenCalledTimes(2);
  });
});
