import { createRouter, createWebHashHistory } from "vue-router";
import ChildrenRoutes from "./ChildrenRouters";
import { getToken } from "../utils/auth";

let mainRouterChildren = [];

mainRouterChildren = mainRouterChildren.concat(ChildrenRoutes)

const routers = [
  {
    path: '/',
    name: 'MainLayout',
    redirect: '/home',
    component: () => import('../views/MainLayout.vue'),
    children: mainRouterChildren
  },
  {
    path: '/login',
    name: 'Login',
    component: () => import('../views/Login/Login.vue')
  }
]

const router = createRouter({
  history: createWebHashHistory(),
  routes: routers
})


router.beforeEach((to, from, next) => {
  const hasToken = getToken()
  if (hasToken) {
    next()
  } else {
    if(to.path === '/login') {
      next()
    } else {
      next({path: '/login', replace: true})
    }
  }
})
export default router
