// eslint-disable-next-line no-unused-vars
import { guards, titleGuard } from '@/router/guards'
import { createRouter, createWebHistory } from 'vue-router'

const routeModules = import.meta.glob('@/features/**/router.js', { eager: true })
const routes = Object.values(routeModules).flatMap((mod) => mod.default || [])

const router = createRouter({
  history: createWebHistory(),
  routes: [...routes, { path: '/:pathMatch(.*)*', redirect: { name: 'login' } }],
  scrollBehavior(to, from, savedPosition) {
    if (savedPosition) return savedPosition
    if (to.hash) return { el: to.hash }
    return { top: 0 }
  },
})

router.beforeEach((to, from) => {
  for (const guard of guards) {
    const result = guard(to, from)
    if (result !== undefined) return result
  }
  return
})

router.afterEach((to) => titleGuard(to))

export default router
