import { defineStore } from 'pinia'
import { ref } from 'vue'
import { getLoggedUser, logout } from 'src/api/auth'
import { usePermissions } from 'src/composables/usePermissions'

export const useAuthStore = defineStore('auth', () => {
  const user = ref(null)
  const loading = ref(true)
  const { loadPermissions } = usePermissions()

  async function checkSession () {
    loading.value = true
    try {
      user.value = await getLoggedUser()
      // Load permissions from targo-hub using the user's email
      if (user.value && user.value !== 'authenticated') {
        await loadPermissions(user.value)
      }
    } catch {
      user.value = 'authenticated'
    } finally {
      loading.value = false
    }
  }

  return { user, loading, checkSession, doLogout: logout }
})
