import { defineStore } from "pinia";
import { login as loginApi, loginout as logoutApi } from "@/api/account";
import { refreshToken as refreshTokenApi } from "@/api/auth";
import { useRouter } from "vue-router";
import { useImStore } from "@/store/im";

export const authStore = defineStore("auth", {
  state: () => ({
    accessToken: sessionStorage.getItem("accessToken") || "",
    refreshToken: sessionStorage.getItem("refreshToken") || "",
    isLoggingIn: false,
    isRefreshing: false,
  }),

  getters: {
    isAuthenticated: (state) => !!state.accessToken,
  },

  actions: {
    /**
     * 用户登录
     * @param {object} credentials - 登录凭证 { username, password, corpId, platform }
     * @returns {Promise}
     */

    async setAccessToken(accessToken) {
      this.accessToken = accessToken;
      sessionStorage.setItem("accessToken", accessToken);
    },
    async setRefreshToken(refreshToken) {
      this.refreshToken = refreshToken;
      sessionStorage.setItem("refreshToken", refreshToken);
    },


    /**
     * 刷新 Token
     * @returns {Promise<string|null>} 返回新的 accessToken，失败返回 null
     */
    async refreshAccessToken() {
      if (!this.refreshToken) {
        console.warn("没有 refreshToken，无法刷新");
        return null;
      }

      if (this.isRefreshing) {
        // 避免并发刷新
        await new Promise((resolve) => setTimeout(resolve, 100));
        return this.accessToken;
      }

      this.isRefreshing = true;

      try {
        const result = await refreshTokenApi(this.refreshToken);

        if (result.success && result.data) {
          // 更新 token
          this.accessToken = result.data.accessToken;
          sessionStorage.setItem("accessToken", result.data.accessToken);

          return result.data.accessToken;
        } else {
          // 刷新失败，清除登录状态
          console.error("Token 刷新失败:", result.message);
          this.logout();
          return null;
        }
      } catch (error) {
        console.error("Token 刷新异常:", error);
        this.logout();
        return null;
      } finally {
        this.isRefreshing = false;
      }
    },

    /**
     * 退出登录
     */
    async logout() {
      // 清除本地存储
      // const imStore = useImStore();
      // await imStore.imLogout();

      this.accessToken = "";
      this.refreshToken = "";
      this.userInfo = null;
      sessionStorage.removeItem("accessToken");
      sessionStorage.removeItem("refreshToken");
    },
  },
});
