export function wrapGraphQLClient(client, subscriptionsClient, onError, retries = 3) {
    return {
        client,
        subscriptionsClient,
        async mutate(resolved, options) {
            if (!options)
                options = {};
            if (options.noCache === undefined)
                options.noCache = true;
            let err;
            for (let tries = 1; tries <= retries; tries++) {
                try {
                    const result = await client.resolve(({ mutation }) => resolved(mutation), options);
                    return result;
                }
                catch (error) {
                    err = error;
                    if (error.message !== 'database query error')
                        break;
                    await new Promise((resolve) => setTimeout(resolve, 1_000 * tries + 1_000));
                }
            }
            if (onError)
                throw onError(err) || err;
            throw err;
        },
        async query(resolved, options) {
            let err;
            for (let tries = 1; tries <= retries; tries++) {
                try {
                    const result = await client.resolve(({ query }) => resolved(query), options);
                    return result;
                }
                catch (error) {
                    err = error;
                    if (error.message !== 'database query error')
                        break;
                    await new Promise((resolve) => setTimeout(resolve, 1_000 * tries + 1_000));
                }
            }
            if (onError)
                throw onError(err) || err;
            throw err;
        },
        subscribe(resolved, onData, onError) {
            if (!subscriptionsClient)
                throw new Error('Subscriptions not enabled');
            let unsub;
            const stop = async () => {
                if (!unsub)
                    return;
                await unsub().catch(() => undefined);
            };
            client.resolved(() => resolved(client.subscription), {
                onSubscription(event) {
                    if (event.unsubscribe)
                        unsub = event.unsubscribe;
                    if (event.type === 'data')
                        onData(event.data, stop);
                    else if (event.type === 'with-errors' && onError)
                        onError(event.error, stop);
                },
            });
            return stop;
        },
    };
}
