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

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

    const userRoles = computed(() => {
      return user.value?.roles || []
    })

    const userActiveRole = ref('') // watched user failed, so create a ref here
    // computed(() => {
    //   // return user.value?.activeRole || ''
    // })

    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
        userActiveRole.value = role
      }
    }

    const getActiveRole = (): string | undefined => {
      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 undefined
    }

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