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

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

import ModuleMetadata from "@/modules/01_metadata/router";
import ModuleUser from "@/modules/02_users/router";
import ModuleLogs from "@/modules/03_logs/router";
import ModuleSystem from "@/modules/04_system/router";
import ModuleCommand from "@/modules/05_command/router";
import ModuleWebServices from "@/modules/06_webservices/router";
import ModeuleIssues from "@/modules/07_issues/router";

// TODO: ใช้หรือไม่?
import { authenticated, logout } from "@/plugins/auth";

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: ["SUPER_ADMIN", "ADMIN"],
          },
        },
        {
          path: "/check-workflow",
          name: "check-workflow",
          component: CheckWorkflow,
          meta: {
            Auth: true,
            Key: [7],
            Role: ["SUPER_ADMIN", "ADMIN"],
          },
        },
        ...ModuleMetadata,
        ...ModuleUser,
        ...ModuleLogs,
        ...ModuleSystem,
        ...ModuleCommand,
        ...ModuleWebServices,
        ...ModeuleIssues,
      ],
    },
    /**
     * 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,
    },

    // authen with keycloak client
    {
      path: "/login",
      name: "loginMain",
      component: loginView,
      meta: {
        Auth: false,
      },
    },
    {
      path: "/auth",
      name: "auth",
      component: () => import("@/views/auth.vue"),
    },
  ],

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

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

export default router;
