"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.createClientV2 = void 0;
const subscriptions_1 = require("@gqty/subscriptions");
const cross_fetch_1 = __importDefault(require("cross-fetch"));
const gqty_1 = require("gqty");
const gqty_2 = require("./gqty");
const wrap_1 = require("./wrap");
function createClientV2(graphqlUri, args) {
    const $headers = args && 'headers' in args ? args.headers : undefined;
    const $fetch = (args && 'fetch' in args ? args.fetch : undefined) || cross_fetch_1.default;
    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 = (0, subscriptions_1.createSubscriptionsClient)({
            wsEndpoint: wsUrl.href,
            connectionInitPayload: async () => ({ headers: await getHeaders() }),
        });
        return subscriptionsClient;
    })();
    const client = (0, gqty_1.createClient)({
        schema: gqty_2.generatedSchema,
        scalarsEnumsHash: gqty_2.scalarsEnumsHash,
        queryFetcher,
        subscriptionsClient,
        normalization: args?.normalization !== false,
        defaults: {
            resolved: {
                noCache: args?.cache ? false : true,
                retry: false,
            },
        },
        ...args,
    });
    return (0, wrap_1.wrapGraphQLClient)(client, subscriptionsClient, args?.onError);
}
exports.createClientV2 = createClientV2;
