import { setSessionId, setToken } from "@/auth/auth";
import { RoleCode } from "@/types";
import { defineStore } from "pinia";

// main is the name of the store. It is unique across your application
// and will appear in devtools
export const useMainStore = defineStore("main", {
  // a function that returns a fresh state
  state: () => {
    return {
      globalMask: false,
      userInfo: {
        userId: -1,
        identity: "",
        displayName: "",
        rootOrgId: -1,
        rootOrgName: "",
        token: "",
        role: 'COURSE_ADMIN' as RoleCode,
      },
      currentLocation: "",
    };
  },
  getters: {
    isSuperAdmin(): boolean {
      return this.userInfo.role === "SUPER_ADMIN";
    },
    isRootOrgAdmin(): boolean {
      return this.userInfo.role === "ROOT_ORG_ADMIN";
    },
    isOrgAdmin(): boolean {
      return this.userInfo.role === "ORG_ADMIN";
    },
    isGreaterThanEqualRootOrgAdmin(): boolean {
      return this.isSuperAdmin || this.isRootOrgAdmin;
    },
    isGreaterThanEqualOrgAdmin(): boolean {
      return this.isSuperAdmin || this.isRootOrgAdmin || this.isOrgAdmin;
    },
    isCourseAdmin():boolean {
      return this.userInfo.role === "COURSE_ADMIN";
    }
  },
  actions: {
    setUserInfo(res: any) {
      this.userInfo = res;
      setToken(this.userInfo.token);
      setSessionId(this.userInfo.identity);
    },
  },
});

setTimeout(() => {
  const store = useMainStore();
  store.$subscribe((_, state) =>
    sessionStorage.setItem("appState", JSON.stringify(state))
  );
  const state = JSON.parse(
    sessionStorage.getItem("appState") || "{}"
  ) as ReturnType<typeof useMainStore>;
  if (state.userInfo?.token) {
    Object.assign(store, state);
  }
}, 0);
