import { defineStore } from "pinia";
import { api, clearTokens } from "../api/client";
import { filterShowMenus } from "../lib/menu";
import { runAdminShellLogoutCleanup } from "../lib/shell";
import { setServicePerms } from "../service";
let loadFlight = null;
export const useUserStore = defineStore("user", {
  state: () => ({
    adminId: 0,
    username: "",
    isSuper: false,
    perms: [],
    menus: [],
    loaded: false
  }),
  getters: {
    navMenus(state) {
      return filterShowMenus(state.menus);
    }
  },
  actions: {
    async load() {
      if (this.loaded)
        return;
      if (loadFlight)
        return loadFlight;
      loadFlight = (async () => {
        try {
          const [me, authz] = await Promise.all([
            api.me({ toast: false }),
            api.perms({ toast: false })
          ]);
          this.adminId = me.adminId;
          this.username = me.username || `admin#${me.adminId}`;
          this.isSuper = authz.isSuper;
          this.perms = Array.isArray(authz.perms) ? authz.perms : [];
          this.menus = Array.isArray(authz.menus) ? authz.menus : [];
          this.loaded = true;
          setServicePerms(this.perms, this.isSuper);
        } finally {
          loadFlight = null;
        }
      })();
      return loadFlight;
    },
    async reloadMenus() {
      const authz = await api.perms({ toast: false });
      this.isSuper = authz.isSuper;
      this.perms = Array.isArray(authz.perms) ? authz.perms : [];
      this.menus = Array.isArray(authz.menus) ? authz.menus : [];
      setServicePerms(this.perms, this.isSuper);
    },
    hasPerm(code) {
      if (this.isSuper)
        return true;
      const codes = Array.isArray(code) ? code : [code];
      return codes.some((c) => this.perms.includes(c));
    },
    logout() {
      runAdminShellLogoutCleanup();
      clearTokens();
      loadFlight = null;
      this.$reset();
    }
  }
});
