import { defineStore } from "pinia";

export const useUserStore = defineStore("user", {
  state: () => {
    const cached = (() => {
      try {
        const raw = sessionStorage.getItem("userInfo");
        return raw ? JSON.parse(raw) : null;
      } catch {
        return null;
      }
    })();
    return {
      userInfo: cached || null,
      authToken: cached?.token || sessionStorage.getItem("authToken") || "",
    };
  },
  getters: {
    isTgbu: (state) =>
      state.userInfo?.departs?.some(
        (r) => r.parentIds?.includes("41") || r.id == "41",
      ) ?? false,
    isXmtb: (state) =>
      state.userInfo?.roles?.some((r) => r.key?.includes("company_dep")) ??
      false,
    isAdmin: (state) =>
      state.userInfo?.roles?.some((r) => r.key === "admin") ?? false,
  },
  actions: {
    setUseInfo(data) {
      this.userInfo = data;
      this.authToken = data.token;
      sessionStorage.setItem("authToken", data.token);
      sessionStorage.setItem("userInfo", JSON.stringify(data));
    },
    clearUserInfo() {
      this.userInfo = null;
      this.authToken = "";
      sessionStorage.removeItem("authToken");
      sessionStorage.removeItem("userInfo");
    },
  },
});
