import * as rest from '@interopio/gateway/metrics/publisher/rest';
import {IOGateway} from '@interopio/gateway';
import {CookieAgent} from 'http-cookie-agent/undici';
import {CookieJar} from 'tough-cookie';

export const fetchWithCookies = (existing?: rest.Fetch): rest.Fetch => {
    const fetchFn = existing ?? rest.fetchWithTimeout();
    // eslint-disable-next-line @typescript-eslint/no-explicit-any
    const jar: any = new CookieJar();
    const dispatcher = new CookieAgent({cookies: {jar}});
    return async (endpoint: string | URL, request: Omit<RequestInit, 'signal'>, timeout: number) => {
        const requestWithDispatcher = {...request, dispatcher};
        return await fetchFn(endpoint, requestWithDispatcher, timeout);
    }
}
export const name = rest.name;

export function create(cfg: rest.RestPublisherConfig, logger: IOGateway.Logging.Logger) {
    return rest.create({...cfg, fetch: fetchWithCookies(cfg.fetch)}, logger);
}
