// 用户信息 Store
import { defineStore } from "pinia";
import { reactive, ref } from "vue";

const STORAGE_TOKEN = "csm_token";
const STORAGE_USER = "csm_user";

const readUser = () => {
  try {
    const raw = localStorage.getItem(STORAGE_USER);
    return raw ? JSON.parse(raw) : null;
  } catch {
    return null;
  }
};

export const useUserStore = defineStore(
  "user",
  () => {
    const token = ref(localStorage.getItem(STORAGE_TOKEN) || "");
    const userInfo = reactive(readUser() || {});

    const setToken = (val) => {
      token.value = val || "";
      console.log("设置 token", val);
      if (val) localStorage.setItem(STORAGE_TOKEN, val);
      else localStorage.removeItem(STORAGE_TOKEN);
    };

    const setUserInfo = (info) => {
      Object.keys(userInfo).forEach((k) => delete userInfo[k]);
      Object.assign(userInfo, info || {});
      localStorage.setItem(STORAGE_USER, JSON.stringify(userInfo));
    };

    const clear = () => {
      token.value = "";
      Object.keys(userInfo).forEach((k) => delete userInfo[k]);
      localStorage.removeItem(STORAGE_TOKEN);
      localStorage.removeItem(STORAGE_USER);
    };

    return {
      token,
      userInfo,
      setToken,
      setUserInfo,
      clear,
    };
  },
  {
    persist: false, // 已自行持久化到 localStorage，避免重复存储
  },
);
