import { useAuthStore } from '@/stores/authStore'
import { nextTick } from 'vue'
import { createRouter, createWebHistory } from 'vue-router'
import { routes } from './routes'

const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes,
})

let isProfileFetched = false

router.beforeEach(async (to, from, next) => {
  const auth = useAuthStore()

  if (!isProfileFetched && auth.isAuthenticated === null) {
    try {
      await auth.fetchProfile()
      await nextTick()
    } catch (err) {
      auth.forceLogout()
    } finally {
      isProfileFetched = true
    }
  }

  const isLoggedIn = auth.isAuthenticated
  const requiresAuth = to.meta.requiresAuth ?? true

  const publicPages = ['/login', '/register']
  const isPublicPage = publicPages.includes(to.path)

  if (requiresAuth && !isLoggedIn && !isPublicPage) {
    return next({
      path: '/login',
      query: {
        ...to.query,
        to: to.fullPath,
      },
    })
  }

  if (isLoggedIn && isPublicPage) {
    const target = typeof to.query.to === 'string' && to.query.to ? to.query.to : '/dashboard'
    return next(target)
  }

  const allowedRoles = to.meta.roles
  const currentRole = auth.user?.data?.role ?? auth.user?.role

  if (allowedRoles && !allowedRoles.includes(currentRole)) {
    return next('/dashboard')
  }

  return next()
})

export function installRouter(app) {
  app.use(router)
}

export { router }

