import { createSubscriptionsClient } from '@gqty/subscriptions';
import fetch from 'cross-fetch';
import { createClient, } from 'gqty';
import { generatedSchema, scalarsEnumsHash, } from './gqty';
import { wrapGraphQLClient } from './wrap';
export function createClientV2(graphqlUri, args) {
    const $headers = args && 'headers' in args ? args.headers : undefined;
    const $fetch = (args && 'fetch' in args ? args.fetch : undefined) || fetch;
    const getHeaders = $headers && typeof $headers === 'function'
        ? () => Promise.resolve($headers())
        : async () => {
            const headers = $headers || {};
            if (args && 'secret' in args) {
                headers['x-hasura-admin-secret'] = args.secret;
            }
            else if (args && 'accessToken' in args && args.accessToken) {
                headers.authorization = args.accessToken.startsWith('Bearer ')
                    ? args.accessToken
                    : `Bearer ${args.accessToken}`;
            }
            return headers;
        };
    const queryFetcher = async (query, variables, fetchOptions) => {
        const headers = await getHeaders();
        if (fetchOptions?.headers) {
            for (const key in fetchOptions.headers) {
                headers[key] = fetchOptions.headers[key];
            }
        }
        const response = await $fetch(graphqlUri, {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
                ...headers,
            },
            body: JSON.stringify({
                query,
                variables,
            }),
        });
        const json = await response.json();
        return json;
    };
    const subscriptionsClient = (() => {
        if (args?.subscriptions === false)
            return;
        const wsUrl = new URL(graphqlUri);
        wsUrl.protocol = wsUrl.protocol
            .replace('https', 'wss')
            .replace('http', 'ws');
        const subscriptionsClient = createSubscriptionsClient({
            wsEndpoint: wsUrl.href,
            connectionInitPayload: async () => ({ headers: await getHeaders() }),
        });
        return subscriptionsClient;
    })();
    const client = createClient({
        schema: generatedSchema,
        scalarsEnumsHash,
        queryFetcher,
        subscriptionsClient,
        normalization: args?.normalization !== false,
        defaults: {
            resolved: {
                noCache: args?.cache ? false : true,
                retry: false,
            },
        },
        ...args,
    });
    return wrapGraphQLClient(client, subscriptionsClient, args?.onError);
}
