import { defineStore } from 'pinia'
import { ref, computed } from 'vue'
import { login as apiLogin, getUserInfo as apiGetUserInfo } from '@/api'

const TOKEN_KEY = import.meta.env.VITE_APP_TOKEN_KEY

export const useUserStore = defineStore('user', () => {
  const token = ref(localStorage.getItem(TOKEN_KEY) || '')
  const name = ref('')
  const roles = ref<string[]>([])
  const avatar = ref('')

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

  /** 登录：获取并存储 Token */
  async function login(username: string, password: string) {
    const res = await apiLogin(username, password)
    token.value = res.data.token
    localStorage.setItem(TOKEN_KEY, res.data.token)
  }

  /** 获取用户信息（在路由守卫中调用） */
  async function getUserInfo() {
    const res = await apiGetUserInfo(token.value)
    name.value = res.data.name
    roles.value = res.data.roles
    avatar.value = res.data.avatar
    return res.data.roles
  }

  /** Token 过期时仅清除 Token，不跳转 */
  function resetToken() {
    token.value = ''
    localStorage.removeItem(TOKEN_KEY)
  }

  /** 登出：清除所有状态，刷新页面清除动态路由 */
  function logout() {
    token.value = ''
    name.value = ''
    roles.value = []
    localStorage.removeItem(TOKEN_KEY)
    // 刷新页面是最可靠的清除动态路由方式
    window.location.replace('/auth')
  }

  return { token, name, roles, avatar, isLoggedIn, login, getUserInfo, resetToken, logout }
})
