import { defineStore } from 'pinia'
import { ref, computed } from 'vue'
import { login as apiLogin, getMe } from '@/api/auth'
import type { UserInfo } from '@/api/auth'

export const useUserStore = defineStore('user', () => {
  const token = ref<string | null>(localStorage.getItem('pdg_token') || null)
  const userInfo = ref<UserInfo | null>(null)
  const isLoggedIn = computed(() => !!token.value)

  async function login(username: string, password: string) {
    const res = await apiLogin(username, password)
    token.value = res.access_token
    localStorage.setItem('pdg_token', res.access_token)
    localStorage.setItem('pdg_refresh', res.refresh_token)
    await fetchUserInfo()
    return res
  }

  async function fetchUserInfo() {
    if (!token.value) return
    try {
      const res = await getMe()
      userInfo.value = res
    } catch (e) {
      logout()
      throw e
    }
  }

  function logout() {
    token.value = null
    userInfo.value = null
    localStorage.removeItem('pdg_token')
    localStorage.removeItem('pdg_refresh')
  }

  return {
    token,
    userInfo,
    isLoggedIn,
    login,
    fetchUserInfo,
    logout,
  }
})
