import { defineStore } from "pinia";

import { fetchMe, loginWithSms, updateMe, type AuthUser } from "@/features/auth/api/auth";
import { clearAuthStorage, getAccessToken, getRefreshToken, setAuthTokens } from "@/utils/authStorage";

export const useSessionStore = defineStore("session", {
  state: () => ({
    token: getAccessToken("user"),
    refreshToken: getRefreshToken("user"),
    userId: Number(localStorage.getItem("user_id") || 0),
    phone: localStorage.getItem("phone") || "",
    nickname: localStorage.getItem("nickname") || "",
    avatarUrl: localStorage.getItem("avatar_url") || "",
    realnameStatus: localStorage.getItem("realname_status") || "unknown",
    _loadingMe: false, // 防止重复调用
  }),
  getters: {
    isLoggedIn: (state) => Boolean(state.token),
    displayName: (state) =>
      state.nickname ||
      (state.phone
        ? `用户${state.phone.slice(-6)}`
        : `用户${state.userId || 0}`),
    avatarText: (state) => (state.nickname || state.phone || "U").slice(0, 1),
  },
  actions: {
    async login(phone: string, code: string) {
      const result = await loginWithSms(phone, code);
      this.applySession(
        result.user,
        result.tokens.access_token,
        result.tokens.refresh_token
      );
      return result;
    },
    async loadMe() {
      if (this._loadingMe) {
        // 如果正在加载，等待完成
        await new Promise((resolve) => {
          const checkInterval = setInterval(() => {
            if (!this._loadingMe) {
              clearInterval(checkInterval)
              resolve(true)
            }
          }, 50)
        })
        return
      }

      this._loadingMe = true
      try {
        const user = await fetchMe();
        this.applyUser(user);
        return user;
      } finally {
        this._loadingMe = false
      }
    },
    async updateProfile(payload: { nickname: string; avatar_url: string }) {
      const user = await updateMe(payload);
      this.applyUser(user);
      return user;
    },
    logout() {
      this.token = "";
      this.refreshToken = "";
      this.userId = 0;
      this.phone = "";
      this.nickname = "";
      this.avatarUrl = "";
      this.realnameStatus = "unknown";
      clearAuthStorage("user");
    },
    syncFromStorage() {
      this.token = getAccessToken("user");
      this.refreshToken = getRefreshToken("user");
      this.userId = Number(localStorage.getItem("user_id") || 0);
      this.phone = localStorage.getItem("phone") || "";
      this.nickname = localStorage.getItem("nickname") || "";
      this.avatarUrl = localStorage.getItem("avatar_url") || "";
      this.realnameStatus = localStorage.getItem("realname_status") || "unknown";
    },
    applySession(user: AuthUser, accessToken: string, refreshToken: string) {
      this.token = accessToken;
      this.refreshToken = refreshToken;
      this.userId = user.id;
      setAuthTokens("user", {
        access_token: accessToken,
        refresh_token: refreshToken,
      });
      localStorage.setItem("user_id", String(user.id));
      this.applyUser(user);
    },
    applyUser(user: AuthUser) {
      this.userId = user.id;
      localStorage.setItem("user_id", String(user.id));
      this.phone = user.phone;
      localStorage.setItem("phone", user.phone);
      this.nickname = user.nickname;
      localStorage.setItem("nickname", user.nickname);
      this.avatarUrl = user.avatar_url;
      localStorage.setItem("avatar_url", user.avatar_url);
      this.realnameStatus = user.realname_status;
      localStorage.setItem("realname_status", user.realname_status);
    },
  },
});
