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

export const useTeamsStore = defineStore('teams', () => {
  const teamsList = ref<any[]>([])
  const hasFetched = ref(false) 
  const isLoading = ref(false)
  
  const fetchTeams = async (forceRefresh = false) => {
    if (hasFetched.value && !forceRefresh) {
      return teamsList.value
    }
    
    isLoading.value = true
    try {
      const response = await fetch('/api/teams')
      const data = await response.json()
      
      teamsList.value = Array.isArray(data) ? data : (data?.data ?? [])
      
      hasFetched.value = true  // 标记为已获取
      return teamsList.value
    } catch (error) {
      console.error('获取teams失败:', error)
      throw error
    } finally {
      isLoading.value = false
    }
  }
  
  const ensureTeamsLoaded = async () => {
    if (!hasFetched.value) {        
      await fetchTeams()
    }
  }
  
  fetchTeams(true).catch(() => {})
  
  return {
    teamsList,
    isLoading,
    hasFetched,
    fetchTeams,
    ensureTeamsLoaded
  }
})
