import { createRouter, createWebHashHistory } from "vue-router";
import { constantRoutes } from "./route";
import { useUserStore } from "@/stores/api/user";

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

const WHITE_LIST = ["/login"];

router.beforeEach((to, from, next) => {
  const userStore = useUserStore();
  const token = userStore.token;
  const userType = userStore.userInfo?.userType;

  // 未登录
  if (!token) {
    if (WHITE_LIST.includes(to.path)) {
      return next();
    }
    return next({ path: "/login", replace: true });
  }

  // // 已登录访问登录页 → 跳到对应端首页
  // if (to.path === "/login") {
  //   if (userType === "Admin") return next({ path: "/admin/orders", replace: true });
  //   if (userType === "Hospital") return next({ path: "/hospital/workbench", replace: true });
  //   return next({ path: "/login", replace: true });
  // }

  // // 端权限校验
  // const needRole = to.matched.find((r) => r.meta?.role)?.meta?.role;
  // if (needRole && needRole !== "public" && needRole !== userType) {
  //   if (userType === "Admin") return next({ path: "/admin/orders", replace: true });
  //   if (userType === "Hospital") return next({ path: "/hospital/workbench", replace: true });
  //   return next({ path: "/login", replace: true });
  // }

  next();
});

export default router;
