import { createRouter, createWebHistory } from "vue-router";

const MainLayout = () => import("@/views/MainLayout.vue");
const Dashboard = () => import("@/views/Dashboard.vue");
const Error404NotFound = () => import("@/views/Error404NotFound.vue");

import ModuleMetadata from "@/modules/01_metadata/router";
import ModuleOrganizational from "@/modules/02_organizational/router";
import ModuleRecruiting from "@/modules/03_recruiting/router";
import ModuleRegistry from "@/modules/04_registry/router";
import ModulePlacement from "@/modules/05_placement/router";
import ModuleRetirement from "@/modules/06_retirement/router";
import ModuleInsignia from "@/modules/07_insignia/router";
import ModuleRegistryEmployee from "@/modules/08_registryEmployee/router";
import ModuleCoin from "@/modules/09_coin/router";
import ModuleOrder from "@/modules/10_order/router";

// TODO: ใช้หรือไม่?
import keycloak from "@/plugins/keycloak";

const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes: [
    {
      path: "/",
      name: "home",
      component: MainLayout,
      children: [
        {
          path: "/",
          name: "dashboard",
          component: Dashboard,
          meta: {
            Auth: true,
            Key: [7],
            Role: "dashboard",
          },
        },
        ...ModuleMetadata,
        ...ModuleOrganizational,
        ...ModuleRecruiting,
        ...ModuleRegistry,
        ...ModulePlacement,
        ...ModuleRetirement,
        ...ModuleInsignia,
        ...ModuleRegistryEmployee,
        ...ModuleCoin,
        ...ModuleOrder,
      ],
    },
    /**
     * 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,
    },
  ],

  scrollBehavior(to, from, savedPosition) {
    if (savedPosition) {
      return savedPosition;
    } else if (to.hash) {
      return {
        el: to.hash,
        behavior: "smooth",
      };
    }
  },
});

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);
      const role = keycloak.tokenParsed?.role;
      if (role.includes(to.meta.Role)) {
        next();
      } else {
        next({ path: "" });
        // next();
      }
    }
  } else {
    next();
  }
  //   next();
});

export default router;
