import { createRouter, createWebHistory } from "vue-router";
import { storage } from "@/utils/storage";

const rootPath = import.meta.env.VITE_ROOT_PATH;

const routes = [
  {
    path: "/",
    component: () => import("@/layouts/default.vue"),
    redirect: { name: "login" },
    children: [
      /** ■ 공용(일반 사용자) 라우트 */
      {
        name: "main",
        path: "/main",
        meta: { title: "", requiresAuth: false },
        component: () => import("@/pages/MainView.vue"),
      },
      {
        name: "select",
        path: "/select",
        meta: { title: "select", requiresAuth: false, hideSidebar: true },
        component: () => import("@/views/Select.vue"),
      },
      {
        name: "home",
        path: "/home",
        meta: { title: "Home", requiresAuth: false },
        component: () => import("@/pages/HomeView.vue"),
      },
      {
        name: "workflows",
        path: "/workflows",
        meta: { title: "Workflows", requiresAuth: false },
        component: () => import("@/pages/WorkflowView.vue"),
      },
      {
        name: "workflow-step-config",
        path: "/workflow-step-config",
        meta: { title: "Workflow Step Config", requiresAuth: false },
        component: () => import("@/pages/WorkflowStepConfigView.vue"),
      },
      {
        name: "run",
        path: "/run/experiment",
        meta: { title: "Run", requiresAuth: false },
        redirect: { name: "experiment" },
        children: [
          {
            name: "experiment",
            path: "/run/experiment",
            meta: { title: "Experiment", requiresAuth: false },
            component: () => import("@/pages/ExperimentView.vue"),
          },
          {
            name: "Executions",
            path: "/run/executions",
            meta: { title: "Executions", requiresAuth: false },
            component: () => import("@/pages/ExecutionsView.vue"),
          },
        ],
      },
      {
        name: "deployment",
        path: "/deployment",
        meta: { title: "Deployment", requiresAuth: false },
        component: () => import("@/pages/DeploymentView.vue"),
      },
      {
        name: "training-script",
        path: "/training-script",
        meta: { title: "Training Script", requiresAuth: true },
        component: () => import("@/pages/TrainingScriptView.vue"),
      },
      {
        name: "datasets",
        path: "/datasets",
        meta: { title: "Datasets", requiresAuth: true },
        component: () => import("@/pages/DatasetView.vue"),
      },

      {
        name: "project",
        path: "/project",
        meta: {
          title: "Projects",
          requiresAuth: false,
          requiresAdmin: true,
        },
        component: () => import("@/pages/ProjectView.vue"),
      },
      {
        name: "users",
        path: "/users",
        meta: {
          title: "Users",
          requiresAuth: false,
          requiresAdmin: true,
        },
        component: () => import("@/pages/UsersView.vue"),
      },
    ],
  },

  /** ■ 인증(로그인/회원가입) */
  {
    name: "login",
    path: "/login",
    meta: { title: "로그인", requiresAuth: false },
    component: () => import("@/pages/LoginView.vue"),
  },
  {
    name: "signup",
    path: "/signup",
    meta: { title: "회원가입", requiresAuth: false },
    component: () => import("@/pages/SignupView.vue"),
  },
];

const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes,
});

router.beforeEach((to) => {
  const authed = !!(
    typeof storage.getToken === "function" && storage.getToken()
  );

  const isLogin = to.name === "login" || to.path === "/login";
  const isSignup = to.name === "signup" || to.path === "/signup";
  const isSelect = to.name === "select" || to.path === "/select";

  const bootDone = sessionStorage.getItem("initialRedirectDone") === "1";

  if (!authed) {
    if (!isLogin && !isSignup) {
      return { name: "login", replace: true, query: { redirect: to.fullPath } };
    }
    return true;
  }

  if (!bootDone && !isSelect && !isLogin && !isSignup) {
    sessionStorage.setItem("initialRedirectDone", "1");
    return { name: "select", replace: true, query: { redirect: to.fullPath } };
  }

  if (to.matched.some((r) => r.meta?.requiresAdmin)) {
    try {
      const raw =
        typeof storage?.getAuth === "function"
          ? storage.getAuth()
          : JSON.parse(localStorage.getItem("autoflow-auth") || "null");

      const roles = raw?.userInfo?.roles ?? raw?.roles ?? [];
      const authCd = raw?.userInfo?.authCd ?? raw?.authCd ?? raw?.auth;

      const isAdmin =
        (Array.isArray(roles)
          ? roles.includes("ROLE_ADMIN")
          : roles === "ROLE_ADMIN") || authCd === "ADMIN";

      if (!isAdmin) {
        return { name: "home", replace: true };
      }
    } catch {
      return { name: "home", replace: true };
    }
  }

  return true;
});

export default router;
