import { defineStore } from 'pinia'
import { ref, computed } from 'vue'
import { getToken, setToken as setTokenCookie, removeToken } from '@/utils/auth'
import { login, logout, getUserInfo } from '@/api/auth'
import type { LoginData, User } from '@/types/system'

export const useUserStore = defineStore('user', () => {
  const token = ref<string | undefined>(getToken())
  const userInfo = ref<User | null>(null)

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

  async function loginAction(data: LoginData) {
    const res = await login(data)
    token.value = res.token
    setToken(res.token)
    return res
  }

  async function fetchUserInfo() {
    const res = await getUserInfo()
    userInfo.value = res
    return res
  }

  function setToken(newToken: string) {
    token.value = newToken
    setTokenCookie(newToken)
  }

  async function logoutAction() {
    try {
      await logout()
    } catch {
      // ignore
    }
    token.value = undefined
    userInfo.value = null
    removeToken()
    localStorage.removeItem('login_username')
    localStorage.removeItem('login_remember')
  }

  return {
    token,
    userInfo,
    isLoggedIn,
    loginAction,
    fetchUserInfo,
    logoutAction,
    setToken,
  }
})
