import { store } from 'quasar/wrappers';
import { createStore } from 'vuex';

export interface StateInterface {
  [key: string]: unknown;
}

export default store(function (/* { ssrContext } */) {
  const Store = createStore({
    modules: {},

    // enable strict mode (adds overhead!)
    // for dev mode and --debug builds only
    strict: !!process.env.DEBUGGING,
  });

  return Store;
});

import { defineStore } from 'pinia';
import { api } from 'src/boot/axios';
import { AxiosResponse } from 'axios';
import { LocalStorage } from 'quasar';
import { useUserStore, useSessionStore } from 'src/plugins/user/store';

function loadCurrentSession() {
  const session = LocalStorage.getItem<FG.Session>('session');
  if (session) session.expires = new Date(session.expires);
  return session || undefined;
}

export const useMainStore = defineStore({
  id: 'main',

  state: () => ({
    session: loadCurrentSession(),
    user: undefined as FG.User | undefined,
  }),

  getters: {
    loggedIn() {
      return this.session !== undefined;
    },
    currentUser() {
      if (this.user === undefined) throw 'Not logged in, this should not be called';
      return this.user;
    },
    permissions() {
      return this.user?.permissions || [];
    },
  },

  actions: {
    /** Ininitalize store from saved session
     *  Updates session and loads current user
     */
    async init() {
      if (this.session) {
        const sessionStore = useSessionStore();
        const session = await sessionStore.getSession(this.session.token);
        if (session) {
          this.session = this.session;
          const userStore = useUserStore();
          const user = await userStore.getUser(this.session.userid);
          if (user) this.user = user;
        }
      }
    },

    async login(userid: string, password: string) {
      try {
        const { data } = await api.post<FG.Session>('/auth', { userid, password });
        this.session = data;
        this.session.expires = new Date(this.session.expires);
        LocalStorage.set('session', this.session);
        return true;
      } catch ({ response }) {
        return (<AxiosResponse | undefined>response)?.status || false;
      }
    },

    logout() {
      if (!this.session) return false;

      void api.delete(`/auth/${this.session.token}`);
      this.$patch({
        session: undefined,
        user: undefined,
      });
      LocalStorage.remove('session');
      return true;
    },

    async requestReset(userid: string) {
      return await api
        .post('/auth/reset', { userid })
        .then(() => true)
        .catch(() => false);
    },

    async resetPassword(token: string, password: string) {
      return await api
        .post('/auth/reset', { token, password })
        .then(() => true)
        .catch(({ response }) =>
          response && 'status' in response ? (<AxiosResponse>response).status : false
        );
    },
  },
});