import { defineStore } from 'pinia'
import { ref } from 'vue'
import { polylanSubmitterApiGetUserInfo, marketApiListMarkets, marketApiListUserBets } from '@/api'
import type { Market } from '@/types'
import type { UserInfoOut, UserBetSchema } from '@/api/types.gen'

export const useMarketStore = defineStore('market', () => {
  // State
  const markets = ref<Market[]>([])
  const userInfo = ref<UserInfoOut | undefined>()
  const userBets = ref<UserBetSchema[]>([])
  const isLoading = ref(true)
  const error = ref<string>('')

  // Actions
  const loadUserInfo = async () => {
    try {
      const response = await polylanSubmitterApiGetUserInfo()
      if (response.data) {
        userInfo.value = response.data
      }
    } catch (err) {
      error.value = 'Failed to load user info'
      console.error('Error loading user info:', err)
    }
  }

  const loadMarkets = async () => {
    try {
      const response = await marketApiListMarkets()
      if (response.data) {
        markets.value = response.data as unknown as Market[]
      }
    } catch (err) {
      error.value = 'Failed to load markets'
      console.error('Error loading markets:', err)
    }
  }

  const loadUserBets = async () => {
    try {
      const response = await marketApiListUserBets()
      if (response.data) {
        userBets.value = response.data
      }
    } catch (err) {
      error.value = 'Failed to load user bets'
      console.error('Error loading user bets:', err)
    }
  }

  const initializeMarketPage = async () => {
    isLoading.value = true
    error.value = ''

    try {
      await Promise.all([
        loadUserInfo(),
        loadMarkets(),
      ])

      // Load user bets if authenticated
      if (userInfo.value?.is_authenticated) {
        await loadUserBets()
      }
    } finally {
      isLoading.value = false
    }
  }

  const refreshPage = async () => {
    await Promise.all([
      loadUserInfo(),
      loadMarkets(),
      userInfo.value?.is_authenticated ? loadUserBets() : Promise.resolve(),
    ])
  }

  return {
    // State
    markets,
    userInfo,
    userBets,
    isLoading,
    error,

    // Actions
    loadUserInfo,
    loadMarkets,
    loadUserBets,
    initializeMarketPage,
    refreshPage,
  }
})
