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

export const useAuthStore = defineStore('auth', () => {
  const jwt = ref<string | undefined>(undefined)
  const refreshJwt = ref<string | undefined>(undefined)
  const user = ref<any | undefined>(undefined)
  const roles = ref<string[]>([])

  const isLoggedIn = computed(() => jwt.value !== undefined && user.value !== undefined)

  const token = computed(() => {
    if (jwt.value) {
      return jwt.value
    }
    return sessionStorage.getItem('token')
  })

  const refreshToken = computed(() => {
    if (refreshJwt.value) {
      return refreshJwt.value
    }
    return sessionStorage.getItem('token_refresh')
  })

  function setToken(token: string | undefined) {
    jwt.value = token
  }

  function clearToken() {
    jwt.value = undefined
  }

  function setRefreshToken(token: string | undefined) {
    refreshJwt.value = token
  }

  function clearRefreshToken() {
    refreshJwt.value = undefined
  }

  function setUser(userIn: any | undefined) {
    user.value = userIn
    setRoles(userIn?.roles ?? [])
  }

  function setRoles(rolesIn: string[]) {
    roles.value = rolesIn
  }

  function clearUser() {
    user.value = undefined
  }

  return {
    jwt,
    user,
    roles,
    isLoggedIn,
    token,
    refreshToken,
    setToken,
    clearToken,
    setRefreshToken,
    clearRefreshToken,
    setUser,
    clearUser,
    setRoles,
  }
})
