import { defineStore } from 'pinia'
import { ref, computed } from 'vue'
import * as authApi from '@/api/auth'
import type { UserInfo } from '@/types/api'

export const useUserStore = defineStore('user', () => {
  // State
  const user = ref<UserInfo | null>(null)
  const hasCheckedAuth = ref(false)

  // Getters
  const isLoggedIn = computed(() => !!user.value)
  const isAdmin = computed(() => user.value?.role === 'admin')
  const displayName = computed(() => {
    if (!user.value) return ''
    const roleText = user.value.role === 'admin' ? '管理员' : '用户'
    return `${user.value.username}（${roleText}）`
  })

  // Actions
  async function login(username: string, password: string, remember: boolean = false) {
    const res = await authApi.login({ username, password, remember })
    if (res.success) {
      user.value = res.user
      hasCheckedAuth.value = true
      return res.next || '/'
    }
    throw new Error('登录失败')
  }

  async function logout() {
    try {
      await authApi.logout()
    } finally {
      user.value = null
      hasCheckedAuth.value = false
    }
  }

  async function fetchUserInfo() {
    const res = await authApi.getUserInfo()
    if (res.success) {
      user.value = res.user
      hasCheckedAuth.value = true
      return res.user
    }
    throw new Error('未登录')
  }

  function clearUser() {
    user.value = null
    hasCheckedAuth.value = false
  }

  return {
    user,
    hasCheckedAuth,
    isLoggedIn,
    isAdmin,
    displayName,
    login,
    logout,
    fetchUserInfo,
    clearUser
  }
})