import { defineStore } from 'pinia'
import { ref, computed } from 'vue'
import { getStorage, setStorage, removeStorage } from '@/utils/storage'

export const useUserStore = defineStore('user', () => {
  const token = ref(getStorage('token') || '')
  const nickname = ref(getStorage('nickname') || '游客')
  const phone = ref(getStorage('phone') || '')
  const avatarUrl = ref(getStorage('avatarUrl') || '')
  const isAdmin = ref(getStorage('isAdmin') === '1')

  const isLoggedIn = computed(() => !!token.value)

  function login(userData: { token: string; nickname: string; phone: string; avatarUrl?: string; isAdmin?: number }) {
    token.value = userData.token
    nickname.value = userData.nickname
    phone.value = userData.phone
    avatarUrl.value = userData.avatarUrl || ''
    isAdmin.value = userData.isAdmin === 1
    setStorage('token', userData.token)
    setStorage('nickname', userData.nickname)
    setStorage('phone', userData.phone)
    setStorage('avatarUrl', userData.avatarUrl || '')
    setStorage('isAdmin', String(userData.isAdmin || 0))
  }

  function logout() {
    token.value = ''
    nickname.value = '游客'
    phone.value = ''
    avatarUrl.value = ''
    isAdmin.value = false
    removeStorage('token')
    removeStorage('nickname')
    removeStorage('phone')
    removeStorage('avatarUrl')
    removeStorage('isAdmin')
  }

  return { token, nickname, phone, avatarUrl, isAdmin, isLoggedIn, login, logout }
})
