import {
  createRouter,
  createWebHashHistory,
  createWebHistory,
} from 'vue-router';

import { resetStaticRoutes } from '@vben/utils';

import { createRouterGuard } from './guard';
import { routes } from './routes';

/**
 *  @zh_CN 创建vue-router实例
 */
const router = createRouter({
  history:
    import.meta.env.VITE_ROUTER_HISTORY === 'hash'
      ? createWebHashHistory(import.meta.env.VITE_BASE)
      : createWebHistory(import.meta.env.VITE_BASE),
  // 应该添加到路由的初始路由列表。
  routes,
  scrollBehavior: (to, _from, savedPosition) => {
    if (savedPosition) {
      return savedPosition;
    }
    return to.hash ? { behavior: 'smooth', el: to.hash } : { left: 0, top: 0 };
  },
  // 是否应该禁止尾部斜杠。
  // strict: true,
});

const resetRoutes = () => resetStaticRoutes(router, routes);

// 获取当前 app 类型（admin/site/home），默认 admin
function getAppType(): 'admin' | 'site' | 'home' {
  const path = location.pathname.replace(/^\/+/, '');
  const first = path.split('/')[0];
  if (first === 'site' || first === 'home' || first === 'admin') return first as any;
  return 'admin';
}

// 重写 push，自动补齐 app 前缀
const originPush = router.push.bind(router);
router.push = (to: any) => {
  const route = typeof to === 'string' ? { path: to } : { ...to };
  if (route.path) {
    const parts = route.path.split('/').filter(Boolean);
    if (!['admin', 'site', 'home'].includes(parts[0])) {
      route.path = `/${getAppType()}${route.path.startsWith('/') ? '' : '/'}${route.path}`;
    }
  }
  return originPush(route);
};

// 重写 resolve，保证解析时也有 app 前缀
const originResolve = router.resolve.bind(router);
router.resolve = (to: any, currentLocation?: any) => {
  const route = typeof to === 'string' ? { path: to } : { ...to };
  if (route.path) {
    const parts = route.path.split('/').filter(Boolean);
    if (!['admin', 'site', 'home'].includes(parts[0])) {
      route.path = `/${getAppType()}${route.path.startsWith('/') ? '' : '/'}${route.path}`;
    }
  }
  return originResolve(route, currentLocation);
};

// 创建路由守卫
createRouterGuard(router);

export { resetRoutes, router };
