import useUserStore from "@/stores/modules/user.ts";
import useAuthStore from "@/stores/modules/auth.ts";
import { LOGIN_URL } from "@/config/index.ts";
import router from "@/routers/index";

export const initDynamicRouter = async () => {
  const userStore = useUserStore();
  const authStore = useAuthStore();

  try {
    // 1. 获取菜单列表 && 按钮权限列表
    await authStore.listRouters();
    await authStore.getLoginUserInfo();

    // 2. 判断当前用户是否拥有菜单权限
    if (!authStore.menuList || authStore.menuList.length === 0) {
      userStore.setToken("");
      router.replace(LOGIN_URL);
      return;
    }

    // 3. 添加动态路由（树形结构）
    const addRoutes = (routes: any[], parentName: string | null = null) => {
      routes.forEach((route) => {
        if (route.isFull === "0") {
          router.addRoute(route);
        } else {
          router.addRoute(parentName || "layout", route);
        }
        if (route.children && route.children.length > 0) {
          addRoutes(route.children, route.name);
        }
      });
    };

    addRoutes(authStore.menuList);
  } catch (error) {
    console.error("获取路由失败:", error);
    userStore.setToken("");
    router.replace(LOGIN_URL);
    return Promise.reject(error);
  }
};
