import { defineStore } from 'pinia'
import { ref } from 'vue'

export const userInfoStore = defineStore('userInfo', () => {
  const userInfo = ref<any>({})
  const hasFetched = ref(false) 
  const isLoading = ref(false)
  
  const fetchUserInfo = async (forceRefresh = false) => {
    if (hasFetched.value && !forceRefresh) {
      return userInfo.value
    }
    isLoading.value = true
    try {
      const response = await fetch('/api/user')
      const json = await response.json()
      if (json?.data) {
        userInfo.value = json.data
      } else {
        userInfo.value = json
      }
      hasFetched.value = true  // 标记为已获取
      return userInfo.value
    } catch (error) {
      console.error('获取userInfo失败:', error)
      throw error
    } finally {
      isLoading.value = false
    }
  }
  
  const ensureUserInfoLoaded = async () => {
    if (!hasFetched.value) {
      await fetchUserInfo()
    }
  }

  const clearUserInfo = () => {
    userInfo.value = {}
    hasFetched.value = false
    isLoading.value = false
  }
  
  fetchUserInfo(true).catch(() => {})
  
  return {
    userInfo,
    isLoading,
    hasFetched,
    fetchUserInfo,
    ensureUserInfoLoaded,
    clearUserInfo
  }
})
