import type { App } from 'vue';
import type { RouteRecord } from 'vue-router';

import { createRouter, createWebHistory, createWebHashHistory } from 'vue-router';
import { routes, ALLRoute, WHITE_NAME_LIST } from './routes';
import { useRouteStore } from '/nerv-base/store/modules/route';
import { createPermissionGuard } from '/nerv-lib/saas/router/guard/permission-guard';

// app router
export const router = createRouter({
  history: createWebHashHistory(import.meta.env.VITE_PUBLIC_PATH as string),
  routes: ALLRoute,
  strict: true,
  scrollBehavior: () => ({ left: 0, top: 0 }),
});

// reset router
export function resetRouter() {
  router.getRoutes().forEach((route: RouteRecord) => {
    const { name } = route;
    if (name && !WHITE_NAME_LIST.includes(name as string)) {
      router.hasRoute(name) && router.removeRoute(name);
    }
  });
}

// config router
export function setupRouter(app: App<Element>) {
  app.use(router);
  const routeStore = useRouteStore();
  routeStore.setRoute(routes);
  createPermissionGuard(router, WHITE_NAME_LIST);
}
