import { createRouter, createWebHistory } from 'vue-router'
import HomeView from '@/views/HomeView.vue'
import MapView from '@/views/MapView.vue'
import MainView from '@/views/MainView.vue'

const loginView = () => import('@/views/login.vue')
const resetPasswordView = () => import('@/views/ResetPassword.vue')

import { authenticated, logout } from '@/plugins/auth'

const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes: [
    {
      path: '/',
      name: 'main',
      component: MainView,
      children: [
        {
          path: '/',
          name: 'home',
          component: HomeView,
          meta: {
            Auth: true,
          },
        },
        {
          path: '/map',
          name: 'map',
          component: MapView,
          meta: {
            Auth: true,
          },
        },
        {
          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'),
          meta: {
            Auth: true,
          },
        },
        {
          path: '/history',
          name: 'history',
          component: () => import('@/views/HistoryView.vue'),
          meta: {
            Auth: false,
          },
        },
        /**
         * 404 Not Found
         * ref: https://router.vuejs.org/guide/essentials/dynamic-matching.html#catch-all-404-not-found-route
         */
        {
          path: '/:pathMatch(.*)*',
          name: 'NotFound',
          component: () => import('@/views/ErrorNotFoundPage.vue'),
          meta: {
            Auth: true,
          },
        },
      ],
    },
    // authen with keycloak client
    {
      path: '/login',
      name: 'loginMain',
      component: loginView,
      meta: {
        Auth: false,
      },
    },
    {
      path: '/auth',
      name: 'auth',
      component: () => import('@/views/auth.vue'),
    },
    {
      path: '/reset-password',
      name: 'reset-password',
      component: resetPasswordView,
      meta: {
        Auth: false,
      },
    },
  ],
})

// authen with keycloak client
router.beforeEach(async (to, from, next) => {
  if (to.meta.Auth) {
    const checkAuthen = await authenticated()
    if (!checkAuthen && to.meta.Auth) {
      logout()
    }
  } else {
    next()
  }
  next()
})

export default router
