import { createRouter, createWebHistory } from 'vue-router'
import HomeView from '../views/HomeView.vue'
import Exam from '@/modules/01_exam/router'
import Meta02 from '@/modules/02_meta/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',
      //   name: 'home',
      component: MainLayout,
      children: [
        // {
        //   path: '/',
        //   name: 'dashboard',
        //   component: HomeView,
        //   meta: {
        //     Auth: true,
        //     Key: [7]
        //   }
        // },
        ...Exam
        // ...Meta02
      ]
    },
    /**
     * 404 Not Found
     * ref: https://router.vuejs.org/guide/essentials/dynamic-matching.html#catch-all-404-not-found-route
     */
    //   {
    //     // path: "/:catchAll(.*)*", // TODO: ใช้ pathMatch แทนตามในเอกสารแนะนำ คงไว้เผื่อจำเป็น
    //     path: "/:pathMatch(.*)*",
    //     component: Error404NotFound,
    //   },
    {
      // path: "/:catchAll(.*)*", // TODO: ใช้ pathMatch แทนตามในเอกสารแนะนำ คงไว้เผื่อจำเป็น
      path: '/:pathMatch(.*)*',
      component: Error404NotFound
    }
  ]
})

// const router = createRouter({
//   history: createWebHistory(import.meta.env.BASE_URL),
//   routes: [
//     {
//       path: '/',
//       name: 'home',
//       component: HomeView
//     },
//     {
//       path: '/about',
//       name: 'about',
//       // route level code-splitting
//       // this generates a separate chunk (About.[hash].js) for this route
//       // which is lazy-loaded when the route is visited.
//       component: () => import('../views/AboutView.vue')
//     }
//   ]
// })
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 {
      //   keycloak.updateToken(60);
      next()
    }
  } else {
    next()
  }
  //   next()
})

export default router
