'use strict';

const core = require('./core-787915c4.js');
const index = require('./index-a20d8492.js');
require('./runStore-bfd81991.js');
const index$1 = require('./index-66ca60fa.js');
const Mutations = require('./Mutations-7f7eb38b.js');

function setContext(setter) {
    return new core.ApolloLink(function (operation, forward) {
        var request = core.__rest(operation, []);
        return new core.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 } = index.createStore({
  identity: null,
});
onChangeAuth("identity", (value) => {
  if (value) {
    core.coreState.client.setLink(core.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 }),
        };
      }),
      core.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 core.coreState.client.mutate({ mutation: index$1.src(Mutations.userTokenRefreshMutationGQL) });
  //Set identity at the end to make sure we have the right order
  authStore.identity = request.data.userTokenRefresh;
}

exports.authStore = authStore;
exports.onChangeAuth = onChangeAuth;
