import qs from 'qs';
import { last } from 'rambda';
import fetch from './fetch-with-extras.js';
import fetchWithDiskCache from './fetch-with-disk-cache.js';
export default (diskCacheTimeMs, verifySsl, requestTimeout) => {
    const { usingDiskCache } = fetchWithDiskCache(diskCacheTimeMs);
    return async ({ url, qsParams, cacheFile, headers, hasAnotherPage, }) => {
        const responses = [
            await usingDiskCache(cacheFile('0'), () => fetch(`${url}?${qs.stringify(qsParams(0))}`, {
                headers: headers ? headers() : {},
                verifySsl,
                timeout: requestTimeout,
            })),
        ];
        // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
        while (hasAnotherPage(last(responses))) {
            const previousResponse = last(responses);
            responses.push(
            // eslint-disable-next-line no-await-in-loop
            await usingDiskCache(cacheFile(responses.length.toString()), () => fetch(`${url}?${qs.stringify(qsParams(responses.length, previousResponse))}`, {
                headers: headers ? headers(previousResponse) : {},
                timeout: requestTimeout,
                verifySsl,
            })));
        }
        return responses;
    };
};
