import qs from 'qs';
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, chunkHandler, }) => {
        let pageIndex = 1;
        let lastResponse = await usingDiskCache(cacheFile('0'), () => fetch(`${url}?${qs.stringify(qsParams(0))}`, {
            headers: headers ? headers() : {},
            verifySsl,
            timeout: requestTimeout,
        }));
        await chunkHandler(lastResponse);
        while (hasAnotherPage(lastResponse)) {
            // eslint-disable-next-line no-await-in-loop
            lastResponse = await usingDiskCache(cacheFile(pageIndex.toString()), 
            // eslint-disable-next-line no-loop-func
            () => fetch(`${url}?${qs.stringify(qsParams(pageIndex, lastResponse))}`, {
                headers: headers ? headers(lastResponse) : {},
                timeout: requestTimeout,
                verifySsl,
            }));
            pageIndex += 1;
            // eslint-disable-next-line no-await-in-loop
            await chunkHandler(lastResponse);
        }
    };
};
