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

import { routes } from "./routes";

import { useUserStore } from "@/stores";

let router = createRouter({
  routes: routes,
  mode: "history",
  history: createWebHistory(),
});

router.beforeEach(async (to, from, next) => {
  const uStore = useUserStore();
  const publicPages = [
    "login",
    "register",
    "unauthorized",
    "test-unauthorized",
  ];
  const authRequired = !publicPages.includes(to.name);
  document.title = to.meta.title + " | LADA Express Management Portal";
  if (authRequired && !uStore.user) {
    uStore.returnUrl = to.fullPath;
    next({ name: "login" });
  } else {
    next();
  }
});
export default router;
