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

import { createRouter, createWebHistory } from 'vue-router';
import { ALLRoute, WHITE_NAME_LIST } from './routes';
import { createPermissionGuard } from '/nerv-lib/paas/router/guard/permission-guard';

// app router
let router: any = undefined;

// 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>, modules?: any) {
  const routers: any[] = [];
  if (!modules) {
    modules = import.meta.globEager('/src/router/**/*.ts');
  }
  Object.keys(modules).forEach((key) => {
    const mod = modules[key].default || {};
    const modList = Array.isArray(mod) ? [...mod] : [mod];
    modList[0].path && routers.push(...modList);
  });
  router = createRouter({
    history: createWebHistory(import.meta.env.VITE_PUBLIC_PATH as string),
    routes: [...ALLRoute, ...routers],
    strict: true,
    scrollBehavior: () => ({ left: 0, top: 0 }),
  });
  app.use(router);
  createPermissionGuard(router, WHITE_NAME_LIST);
}
