import { createApp } from 'vue'
import { createPinia } from 'pinia'
import { VueQueryPlugin } from '@tanstack/vue-query'
import App from './App.vue'
import router from './router'
import { queryClient } from './api/queryClient'
import { useAuthStore } from './stores/auth'
import { startBrowserTelemetry } from './services/browserTelemetry'
import { startDomainEventSync } from './services/domainEvents'
import './assets/main.css'
import './assets/nexus-tokens.css'
import './assets/nexus-components.css'

const pinia = createPinia()

router.beforeEach(async to => {
  const auth = useAuthStore(pinia)
  await auth.initialize()

  if (to.meta.public) {
    return to.name === 'Login' && auth.isAuthenticated ? '/dashboard' : true
  }

  if (!auth.isAuthenticated) {
    return { name: 'Login', query: { redirect: to.fullPath } }
  }

  return true
})

createApp(App)
  .use(pinia)
  .use(VueQueryPlugin, { queryClient })
  .use(router)
  .mount('#app')

startBrowserTelemetry(router)
startDomainEventSync(router)
