import { defineStore } from 'pinia'
import {
  computed,
  ref
} from 'vue'
import { isEmpty } from '@/common/utils/strings.ts'
import Evt from '@/common/utils/evt.ts'

export const useAppUserStore = defineStore('AppUser', () => {
  const userId = ref<string | null>(null)
  const nickname = ref<string | null>(null)
  const avatar = ref<string | null>(null)
  const token = ref<string | null>(null)
  const tenantId = ref<string | null>(null)
  const tenantName = ref<string | null>(null)
  const isAuthenticated = computed(() => !isEmpty(token.value))

  function $reset() {
    userId.value = null
    avatar.value = null
    nickname.value = null
    token.value = null
    tenantId.value = null
    tenantName.value = null
  }

  Evt.on('logout', $reset)

  return {
    userId,
    avatar,
    nickname,
    token,
    tenantId,
    tenantName,
    isAuthenticated,
    $reset,
  }
}, {
  persist: {
    paths: [ 'userId', 'avatar', 'nickname', 'token', 'tenantId', 'tenantName' ],
  },
})

