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

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