import { writable, derived } from 'svelte/store';

function createVersionStore() {
  const { subscribe, set, update } = writable({"auth":null});

  return {
    subscribe,

    set: (v) => {
      update((m) => Object.assign(m, v));
    },

    update,

    refresh: async () => {
      const version = await (await fetch('api/version', {headers: {'Accept': 'application/json'}})).json()
      update((m) => version);
      return version;
    },
  };

}

export const version = createVersionStore();

export const auth = derived(
  version,
  $version => $version.auth,
);

function createGitlabStore() {
  const { subscribe, set, update } = writable(null);

  return {
    subscribe,

    set,

    update,

    refresh: async () => {
      const res = await fetch('api/gitlab/token', {headers: {'Accept': 'application/json'}});
      if (res.status === 200) {
        const token = await res.json();
        update((m) => token);
        return token;
      } else {
        update((m) => null);
        return null;
      }
    },
  };

}

export const gitlab = createGitlabStore();
