import type {
  ComponentRecordType,
  GenerateMenuAndRoutesOptions,
} from '@vben/types';

import { generateAccessible } from '@vben/access';
import { preferences } from '@vben/preferences';

import { getAllMenusApi } from '#/api/core/menu';
import { BasicLayout, IFrameView } from '#/layouts';
import { $t } from '#/locales';
import { useAppContextStore } from '#/store/app-context';

const forbiddenComponent = () => import('#/views/_core/fallback/forbidden.vue');

async function generateAccess(options: GenerateMenuAndRoutesOptions) {
  const pageMap: ComponentRecordType = import.meta.glob([
    '../views/_core/agent-chat/**/*.vue',
    '../views/_core/announcement/index.vue',
    '../views/_core/announcement/list.vue',
    '../views/_core/authentication/login.vue',
    '../views/_core/authentication/oauth-callback.vue',
    '../views/_core/chat/index.vue',
    '../views/_core/control-center/index.vue',
    '../views/_core/fallback/**/*.vue',
    '../views/_core/menu/index.vue',
    '../views/_core/message/index.vue',
    '../views/_core/permission/index.vue',
    '../views/_core/role/index.vue',
    '../views/_core/system-config/index.vue',
    '../views/_core/user/index.vue',
    '../views/ai-platform/agent/editor/index.vue',
    '../views/ai-platform/agent/index.vue',
    '../views/ai-platform/knowledge/detail/index.vue',
    '../views/ai-platform/knowledge/index.vue',
    '../views/ai-platform/workflow/editor/index.vue',
    '../views/ai-platform/workflow/index.vue',
    '../views/ai-platform/workflow-runs/index.vue',
  ]);

  const layoutMap: ComponentRecordType = {
    BasicLayout,
    IFrameView,
  };

  return await generateAccessible(preferences.app.accessMode, {
    ...options,
    fetchMenuListAsync: async () => {
      const { ElMessage } = await import(
        'element-plus/es/components/message/index'
      );
      ElMessage({
        duration: 1500,
        message: `${$t('common.loadingMenu')}...`,
      });

      // 获取应用上下文
      const appContextStore = useAppContextStore();

      // 如果是子应用模式，传递 appCode 过滤应用专属菜单
      if (appContextStore.appCode) {
        return await getAllMenusApi(appContextStore.appCode);
      }

      // 主应用模式，不传参数
      return await getAllMenusApi();
    },
    // 可以指定没有权限跳转403页面
    forbiddenComponent,
    // 如果 route.meta.menuVisibleWithForbidden = true
    layoutMap,
    pageMap,
  });
}

export { generateAccess };
