import {defineStore} from "pinia";
import {ref} from "vue";
import {login as loginApi, getUserInfo, logout as logoutApi} from "@/api/user.js";

const TOKEN_KEY = 'bm_token'

export const useUserStore = defineStore('user', () => {
    const token = ref(localStorage.getItem(TOKEN_KEY) || '')
    const userInfo = ref({})

    async function login(form) {
        const data = await loginApi(form)
        token.value = data.token
        userInfo.value = data.user
        localStorage.setItem(TOKEN_KEY, data.token)
        return data
    }

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

    async function logout() {
        try {
            await logoutApi()
        } catch (_) {

        }
        token.value = ''
        userInfo.value = {}
        localStorage.removeItem(TOKEN_KEY)
    }

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

})