import { QoreClient } from "@qorebase/client";
import createQoreContext from "@qorebase/react";
import { DefaultApiFactory } from "@qorebase/sdk";
import Cookies from "js-cookie";
import getConfig from "next/config";
import React from "react";
import { staleMemoize } from "@qorebase/app-runtime/src/utils/staleMemoize";
const { serverRuntimeConfig, publicRuntimeConfig } = getConfig();
const isServer = typeof window === "undefined";
const BASE_URL = process.env.NODE_ENV === "development" && !isServer
    ? "/api/backend"
    : publicRuntimeConfig.qoreDataConsoleEndpoint;
export const qoreConfig = {
    endpoint: BASE_URL,
    adminSecret: serverRuntimeConfig.qoreDataConsoleAdminSecret,
    getToken: () => Cookies.get("token"),
};
const client = new QoreClient(qoreConfig);
client.project.axios.defaults.headers["x-qore-engine-admin-secret"] =
    qoreConfig.adminSecret;
const sdk = DefaultApiFactory({
    apiKey: qoreConfig.adminSecret,
    isJsonMime: (mime) => {
        const jsonMime = new RegExp("^(application/json|[^;/ \\t]+/[^;/ \\t]+[+]json)[ \\t]*(;.*)?$", "i");
        return (mime !== null &&
            (jsonMime.test(mime) ||
                mime.toLowerCase() === "application/json-patch+json"));
    },
    accessToken: qoreConfig.getToken(),
}, "", client.project.axios);
export const getStorageToken = staleMemoize(() => sdk.storageToken().then(({ data }) => data.token), 1000 * 60 * 5);
export const useStorageToken = () => {
    const [token, setToken] = React.useState("");
    const tokenRequest = getStorageToken();
    React.useEffect(() => {
        let canceled = false;
        tokenRequest
            .then((token) => {
            if (!canceled) {
                setToken(token);
            }
        })
            .catch(console.error);
        return () => {
            canceled = true;
        };
    }, [tokenRequest]);
    return token;
};
const qoreStorageClient = createQoreContext(client);
// eslint-disable-next-line fp/no-mutating-assign
export default Object.assign(qoreStorageClient, { useStorageToken });
//# sourceMappingURL=qoreStorageClient.js.map