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

import { tokenService } from '@/services/api/token-service'

export const useAuthStore = defineStore('auth', () => {
  const user = ref(tokenService.getUserInfo())

  const isAuthenticated = computed(() => !!tokenService.getToken() && !!user.value)
  const role = computed(() => {
    const u = user.value
    if (!u) return null
    if (Array.isArray(u.roles) && u.roles.length > 0) return u.roles[0]
    return u.role || u.roleName || null
  })

  const setUser = (userData) => {
    user.value = userData
    tokenService.saveUserInfo(userData)
  }

  const clearUser = () => {
    user.value = null
    tokenService.clearAll()
  }

  return {
    user,
    role,
    isAuthenticated,
    setUser,
    clearUser,
  }
})
