"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.useHasuraClientInner = useHasuraClientInner;
const subscriptions_1 = require("@gqty/subscriptions");
// import fetch from 'cross-fetch';
const gqty_1 = require("gqty");
const constants_1 = require("./constants");
const gqty_2 = require("./gqty");
function useHasuraClientInner(args) {
    const $headers = args && 'headers' in args ? args.headers : undefined;
    const $fetch = (args && 'fetch' in args ? args.fetch : undefined) || fetch;
    const uri = args?.uri || constants_1.hasuraGraphqlUri;
    const getHeaders = async (base) => {
        const headers = ($headers && typeof $headers === 'function'
            ? await $headers()
            : $headers) || {};
        if (base)
            for (const key in base)
                headers[key] = base[key];
        if (args && 'secret' in args && args.secret) {
            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}`;
        }
        if (args?.auditUserId)
            headers['x-hasura-audit-user-id'] = args.auditUserId;
        return headers;
    };
    const queryFetcher = async ({ query, variables, operationName }, fetchOptions) => {
        const headers = await getHeaders();
        if (fetchOptions?.headers) {
            for (const key in fetchOptions.headers) {
                headers[key] = fetchOptions.headers[key];
            }
        }
        // Modify "https://finalytic.hasura.app/v1/graphql" if needed
        const response = await $fetch('https://finalytic.hasura.app/v1/graphql', {
            ...fetchOptions,
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
                ...headers,
            },
            body: JSON.stringify({
                query,
                variables,
                operationName,
            }),
            mode: 'cors',
        });
        const json = await response.json();
        return json; //await defaultResponseHandler(json);
    };
    const subscriptionsClient = args?.subscriptions === true
        ? (0, subscriptions_1.createSubscriptionsClient)({
            lazy: true,
            connectionInitPayload: async () => ({
                headers: await getHeaders({
                    [constants_1.hasuraQueryTypeHeader]: 'subscription',
                }),
            }),
            wsEndpoint() {
                const wsUrl = new URL(uri);
                wsUrl.protocol = wsUrl.protocol
                    .replace('https', 'wss')
                    .replace('http', 'ws');
                return wsUrl.href;
            },
            /*url: () => {
            },*/
        })
        : undefined;
    const cache = new gqty_1.Cache(undefined, {
        maxAge: 0,
        staleWhileRevalidate: 0,
        normalization: false,
    });
    const client = (0, gqty_1.createClient)({
        schema: gqty_2.generatedSchema,
        scalars: gqty_2.scalarsEnumsHash,
        //cache,
        cache,
        fetchOptions: {
            fetcher: queryFetcher,
            subscriber: subscriptionsClient,
        },
    });
    /*const client: GQtyClient<GeneratedSchema> = createClient<GeneratedSchema>({
      schema: generatedSchema,
      scalarsEnumsHash,
      queryFetcher,
      subscriptionsClient,
      normalization: args?.normalization === true,
      defaults: {
        resolved: {
          noCache: args?.cache !== true,
          retry: false,
        },
      },
      ...args,
    });*/
    return { subscriptionsClient, client };
}
