import type { App } from 'vue';
import {
  type RouterHistory,
  createMemoryHistory,
  createRouter,
  createWebHashHistory,
  createWebHistory
} from 'vue-router';
import { connect } from '@/utils/webSocket';
import { createBuiltinVueRoutes } from './routes/builtin';
import { createStaticRoutes } from './routes'; // 导入静态路由创建函数
import { createRouterGuard } from './guard';

const { VITE_ROUTER_HISTORY_MODE = 'history', VITE_BASE_URL } = import.meta.env;

const historyCreatorMap: Record<Env.RouterHistoryMode, (base?: string) => RouterHistory> = {
  hash: createWebHashHistory,
  history: createWebHistory,
  memory: createMemoryHistory
};

// 获取静态路由配置
const { constantRoutes } = createStaticRoutes();

// 创建路由器，使用所有常量路由
const routes = [...createBuiltinVueRoutes(), ...constantRoutes];

export const router = createRouter({
  history: historyCreatorMap[VITE_ROUTER_HISTORY_MODE](VITE_BASE_URL),
  routes
});

/** Setup Vue Router */
export async function setupRouter(app: App) {
  app.use(router);
  createRouterGuard(router);
  await router.isReady();
}

router.beforeEach((to, from, next) => {
  connect();
  next();
});
