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

import AdminBackups from "../views/AdminBackups.vue";
import AdminCertificates from "../views/AdminCertificates.vue";
import AdminHome from "../views/AdminHome.vue";
import AdminImports from "../views/AdminImports.vue";
import AdminLogin from "../views/AdminLogin.vue";
import AdminLogs from "../views/AdminLogs.vue";
import AdminLearners from "../views/AdminLearners.vue";
import AdminProjects from "../views/AdminProjects.vue";
import AdminSettings from "../views/AdminSettings.vue";
import AdminTemplates from "../views/AdminTemplates.vue";
import AdminShell from "../views/AdminShell.vue";
import CertificateQuery from "../views/CertificateQuery.vue";
import CertificateView from "../views/CertificateView.vue";
import VerifyView from "../views/VerifyView.vue";

export const router = createRouter({
  history: createWebHistory(),
  routes: [
    { path: "/", redirect: "/query" },
    { path: "/admin/login", component: AdminLogin },
    {
      path: "/admin",
      component: AdminShell,
      children: [
        { path: "", component: AdminHome },
        { path: "projects", component: AdminProjects },
        { path: "templates", component: AdminTemplates },
        { path: "learners", component: AdminLearners },
        { path: "certificates", component: AdminCertificates },
        { path: "imports", component: AdminImports },
        { path: "logs", component: AdminLogs },
        { path: "backups", component: AdminBackups },
        { path: "settings", component: AdminSettings }
      ]
    },
    { path: "/query", component: CertificateQuery },
    { path: "/cert/:token", component: CertificateView },
    { path: "/verify/:token", component: VerifyView }
  ]
});

router.beforeEach((to) => {
  if (to.path.startsWith("/admin") && to.path !== "/admin/login" && !localStorage.getItem("admin_token")) {
    return "/admin/login";
  }
});
