import { A as ApolloLink, _ as __rest, z as zenObservable, c as coreState } from './core-6e4b87fa.js';
import { c as createStore } from './index-2f7827f5.js';
import './runStore-08a7baa7.js';
import { s as src } from './index-313b8a90.js';
import { u as userTokenRefreshMutationGQL } from './Mutations-823a697d.js';

function setContext(setter) {
    return new ApolloLink(function (operation, forward) {
        var request = __rest(operation, []);
        return new zenObservable(function (observer) {
            var handle;
            Promise.resolve(request)
                .then(function (req) { return setter(req, operation.getContext()); })
                .then(operation.setContext)
                .then(function () {
                handle = forward(operation).subscribe({
                    next: observer.next.bind(observer),
                    error: observer.error.bind(observer),
                    complete: observer.complete.bind(observer),
                });
            })
                .catch(observer.error.bind(observer));
            return function () {
                if (handle)
                    handle.unsubscribe();
            };
        });
    });
}

const { state: authStore, onChange: onChangeAuth } = createStore({
  identity: null,
});
onChangeAuth("identity", (value) => {
  if (value) {
    coreState.client.setLink(ApolloLink.from([
      setContext((_, { headers }) => {
        // return the headers to the context so httpLink can read them
        return {
          headers: Object.assign(Object.assign({}, headers), { authorization: value.token }),
        };
      }),
      coreState.client.link,
    ]));
    window.localStorage.setItem("canAuthenticate", "1");
  }
  else {
    document.cookie = "refreshToken=; Path=/; Expires=Thu, 01 Jan 1970 00:00:01 GMT;";
    window.localStorage.removeItem("canAuthenticate");
  }
  return null;
});
initIdentityFromCookie();
async function initIdentityFromCookie() {
  if (!window.localStorage.getItem("canAuthenticate"))
    return;
  const request = await coreState.client.mutate({ mutation: src(userTokenRefreshMutationGQL) });
  //Set identity at the end to make sure we have the right order
  authStore.identity = request.data.userTokenRefresh;
}

export { authStore as a, onChangeAuth as o };
