import { defineStore } from 'pinia'
import useApiFetch from '@/composables/useApiFetch'

export const useUserStore = defineStore('user', {
  state: () => ({
    userName: '',
    mobile: '',
    userAvatar: '',
    isLoggedIn: false,
  }),
  actions: {
    async fetchUserInfo() {
      const { data, error } = await useApiFetch('/user/detail').get().json()
      if (data.value && !error.value) {
        if (data.value.code === 200) {
          const userinfo = data.value.data.userInfo
          this.userName = userinfo.mobile || ''
          this.mobile = userinfo.mobile || ''
          this.userAvatar = userinfo.userAvatar || ''
          this.isLoggedIn = true
          uni.setStorageSync('userInfo', JSON.stringify({ nickName: this.userName, avatar: this.userAvatar }))
        } else if (data.value.code === 100009) {
          uni.removeStorageSync('token')
          uni.removeStorageSync('refreshAfter')
          uni.removeStorageSync('accessExpire')
          uni.removeStorageSync('userInfo')
          uni.removeStorageSync('agentInfo')
          this.resetUser()
          throw new Error('User not found or token invalid')
        } else {
          throw new Error(`Unexpected response code: ${data.value.code}`)
        }
      } else {
        throw error.value || new Error('Unknown error')
      }
    },
    updateUserInfo(userInfo) {
      if (userInfo) {
        this.userName = userInfo.mobile || userInfo.nickName || ''
        this.userAvatar = userInfo.avatar || ''
        this.mobile = userInfo.mobile || this.mobile
        this.isLoggedIn = true
      }
    },
    resetUser() {
      this.userName = ''
      this.mobile = ''
      this.userAvatar = ''
      this.isLoggedIn = false
    },
  },
})
