import { defineStore } from 'pinia'
import { ref } from 'vue'

export const useUserStore = defineStore('user', () => {
    const user = ref(JSON.parse(localStorage.getItem('user') || 'null'))
    const token = ref(localStorage.getItem('token') || '')

    function setLogin(tokenVal, userVal) {
        token.value = tokenVal
        user.value = userVal
        localStorage.setItem('token', tokenVal)
        localStorage.setItem('user', JSON.stringify(userVal))
    }

    function logout() {
        token.value = ''
        user.value = null
        localStorage.removeItem('token')
        localStorage.removeItem('user')
    }

    const isLoggedIn = () => !!token.value
    const getRole = () => user.value?.role || ''

    return { user, token, setLogin, logout, isLoggedIn, getRole }
})
