import {
  createRouter,
  createWebHashHistory,
  createWebHistory,
} from "vue-router";
import Dashboard from "../views/Dashboard.vue";
import Tables from "../views/Tables.vue";
import Billing from "../views/Billing.vue";
import { userRoutes } from "./user.js";
import { roleRoutes } from "./role.js";
import UserLogin from "./../views/user/UserLogin.vue";
import UserSignup from "./../views/user/UserSignup.vue";

const ifAuthenticated = (to, from, next) => {
  if (localStorage.getItem("access_token")) {
    next();
    return;
  }
  router.push({
    path: "/user/login",
    params: {
      returnTo: to.path,
      query: to.query,
    },
  });
};

const routes = [
  {
    path: "/",
    name: "index",
    children: [
      ...userRoutes,
      ...roleRoutes,
      {
        path: "/dashboard",
        name: "Dashboard",
        component: Dashboard,
      },
      {
        path: "/tables",
        name: "Tables",
        component: Tables,
      },
      {
        path: "/billing",
        name: "Billing",
        component: Billing,
      },
    ],
    beforeEnter: ifAuthenticated,
  },
  {
    path: "/user/login",
    name: "user-login",
    component: UserLogin,
  },
  {
    path: "/user/register",
    name: "user-register",
    component: UserSignup,
  },
];

const router = createRouter({
  history: createWebHistory(),
  routes,
  linkActiveClass: "active",
});

export default router;
