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: "dataGroup",
        path: "/datagroup",
        meta: { title: "DataGroup", requiresAuth: false },
        component: () => import("@/pages/DatagroupView.vue"),
      },
      {
        name: "TrainingScriptGroup",
        path: "/trainingscriptgroup",
        meta: { title: "TrainingScriptGroup", requiresAuth: false },
        component: () => import("@/pages/TrainingscriptgroupView.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"),
      },
    ],
  },

  /** ■ 관리자(시스템 상태) - 래퍼 하나로 레이아웃+본문 직접 렌더 (중첩 router-view 없음) */
  {
    path: "/system-status",
    name: "admin",
    meta: { title: "관리자", requiresAuth: false, requiresAdmin: true },
    component: () => import("@/pages/AdminPageWrapper.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, from) => {
  const authed = !!(
    typeof storage.getToken === "function" && storage.getToken()
  );
  const isLogin = to.name === "login";
  const isSignup = to.name === "signup";
  const isSelect = to.name === "select";

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

  const hasProject = !!localStorage.getItem("projectId"); // ✅ 프로젝트 선택 여부
  const bootDone = sessionStorage.getItem("initialRedirectDone") === "1";
  const isAdminRoute = to.name === "admin" || to.name === "project" || to.name === "users" || to.path === "/system-status" || to.meta?.requiresAdmin;

  // 이미 프로젝트 선택됨 → 어떤 화면이든 통과
  if (hasProject) return true;

  // 관리자 전용 페이지는 프로젝트 없이도 접근 허용
  if (isAdminRoute) return true;

  // 아직 프로젝트 미선택
  if (!bootDone) {
    // ✅ 선택 화면에 "들어온 순간"을 부트 완료로 간주 (여기서 한 번만 세팅)
    if (isSelect) {
      sessionStorage.setItem("initialRedirectDone", "1");
      return true;
    }
    // ✅ select 로 1회만 보냄
    return { name: "select", replace: true, query: { redirect: to.fullPath } };
  }

  // 부트 완료인데 여전히 프로젝트 미선택이면, select만 허용
  if (!isSelect) {
    return { name: "select", replace: true, query: { redirect: to.fullPath } };
  }

  return true;
});

export default router;
