export const useUserStore = defineStore(
  'user',
  () => {
    const user = ref<any | null>(null)
    // const token = useCookie('authentication')

    const isAuthenticated = computed(() => !!user.value)

    const userRole = computed(() => {
      return user.value?.roles || []
      // return roles.map((input: string) => {
      //   const parts = input.split('|')
      //   return parts.length > 1 ? parts[1]: parts[0]
      // })
    })

    const login = async (userData: any) => {
      user.value = userData
    }

    const logout = () => {
      user.value = null
    }

    const setActiveRole = (role: string) => {
      if (user.value && user.value.roles.includes(role)) {
        user.value.activeRole = role
      }
    }

    const getActiveRole = () => {
      if (user.value?.activeRole) {
        return user.value.activeRole
      }
      if (user.value?.roles.length > 0) {
        user.value.activeRole = user.value.roles[0]
        return user.value.activeRole
      }
    }

    return {
      user,
      isAuthenticated,
      userRole,
      login,
      logout,
      setActiveRole,
      getActiveRole,
    }
  },
  {
    persist: {
      key: 'user',
      pick: ['user'],
    },
  },
)
