import {create} from 'zustand'

import type {AccountStore} from '../../global/type.tsx'
import {AccountClient} from '../../generated/ManagingApi'
import useApiUrlStore from './apiStore'

export const useAuthStore = create<AccountStore>((set, get) => ({
  accounts: [],
  onInitialize: async () => {
    console.log('useAuthStore onInitialize')
    
    try {
      const { apiUrl } = useApiUrlStore.getState()
      const accountClient = new AccountClient({}, apiUrl)
      const accounts = await accountClient.account_GetAccounts()
      
      if (accounts.length > 0) {
        get().setAccounts(accounts)
        console.log('Accounts loaded:', accounts.length)
      } else {
        console.log('No accounts found')
      }
    } catch (error) {
      console.error('Failed to load accounts:', error)
    }
  },
  setAccounts: (accounts) => {
    set((state) => ({
      ...state,
      accounts: accounts,
    }))
  },
  getFirstAccount: () => {
    const state = get()
    return state.accounts.length > 0 ? state.accounts[0] : null
  },
  getFirstAccountName: () => {
    const state = get()
    return state.accounts.length > 0 ? state.accounts[0].name : ''
  },
}))
