import { createRouter, createWebHistory } from 'vue-router'
import Exam from '@/modules/01_exam/router'

import keycloak from '@/plugins/keycloak'

const MainLayout = () => import('@/views/MainLayout.vue')
const Error404NotFound = () => import('@/views/Error404NotFound.vue')

const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes: [
    {
      path: '/exam/:id',
      component: MainLayout,
      children: [...Exam]
    },
    {
      path: '/:pathMatch(.*)*',
      component: Error404NotFound
    }
  ]
})

router.beforeEach((to, from, next) => {
  if (to.meta.Auth) {
    if (!keycloak.authenticated) {
      keycloak.login({
        redirectUri: `${window.location.protocol}//${window.location.host}${to.path}`,
        locale: 'th'
      })
    } else {
      next()
    }
  } else {
    next()
  }
})

export default router
