// stores/user.ts
import { defineStore } from 'pinia'
import { setAuthToken, clearAuthToken } from '@/utils/auth'
import type { IUserInfo } from '@/types/user'

export const useUserStore = defineStore('user', {
  state: (): IUserInfo => (uni.getStorageSync('userInfo') || {
    id: 0,
    name: '',
    nickname: '',
    avatar: '',
    email: '',
    token: '',
    age: '',
    tel: '',
    sex: '',
  }),

  getters: {
    isLoggedIn: (state: any) => Boolean(state.token),
    userInfo: (state: any) => {
      return state
    },
  },

  actions: {
    /** 设置用户信息（登录成功后调用） */
    setUserInfo(userInfo: IUserInfo) {
      Object.assign(this, userInfo)

      if (userInfo.token) {
        this.token = userInfo.token
        setAuthToken(userInfo.token)
      }

      uni.setStorageSync('userInfo', userInfo)
    },

    /** 设置语言 */
    setLanguage(language: string) {
      this.language = language
      uni.setStorageSync('appLanguage', language)
    },

    /** 登出 */
    logout() {
      try {
        // ✅ 优先使用 Pinia 内置方法（最安全）
        this.$reset()
      } catch (err) {
        // ✅ 如果 $reset 不存在（旧版 pinia），动态清空
        Object.keys(this).forEach((key) => {
          // TS安全地访问 this[key]
          const val = (this as Record<string, any>)[key]
          if (typeof val === 'string') (this as any)[key] = ''
          else if (typeof val === 'number') (this as any)[key] = 0
          else if (Array.isArray(val)) (this as any)[key] = []
          else if (typeof val === 'object' && val !== null) (this as any)[key] = {}
          else (this as any)[key] = undefined
        })
      }

      clearAuthToken()
      uni.removeStorageSync('userInfo')
    },

    /** 从本地存储恢复用户信息 */
    restoreUserInfo() {
      const userInfo = uni.getStorageSync('userInfo')
      if (userInfo) Object.assign(this, userInfo)

      const token = uni.getStorageSync('token')
      if (token) this.token = token
    },
  },
})
