import type { RouteRecordRaw } from 'vue-router'
import type { MenuItemRaw } from '@/api/menu'

/**
 * 组件映射表
 *
 * key   = 后端返回的 component 字符串
 * value = 对应的懒加载组件
 *
 * 【新增页面时】在这里加一条映射即可，后端返回对应的 key 就能自动注册路由
 */
const componentMap: Record<string, () => Promise<any>> = {
  'Jobs':         () => import('@/views/Jobs.vue'),
  'Agent':        () => import('@/views/Agent.vue'),
  'Profile':      () => import('@/views/Profile.vue'),
  'Resume':       () => import('@/views/Resume.vue'),
  'Mentor':       () => import('@/views/Mentor.vue'),
  'Announcement': () => import('@/views/Announcement.vue'),
}

/**
 * 把后端返回的菜单数据转换成 vue-router 能识别的 RouteRecordRaw
 *
 * 如果后端返回了一个 component 字符串在映射表里找不到，会跳过该条路由并打印警告
 * 已在静态路由中注册的路径（如 /jobs）不再重复注册
 */
const STATIC_PATHS = ['/', '/m', '/jobs', '/resume/:id', '/jobs/:id', '/mentor/:id', '/announcement/:id']

export function buildDynamicRoutes(menus: MenuItemRaw[]): RouteRecordRaw[] {
  const routes: RouteRecordRaw[] = []

  for (const item of menus) {
    // 跳过已在静态路由中注册的路径
    if (STATIC_PATHS.includes(item.path)) continue

    const comp = componentMap[item.component]
    if (!comp) {
      console.warn(`[dynamicRoutes] 组件映射表中找不到 "${item.component}"，已跳过`)
      continue
    }
    routes.push({
      path: item.path,
      name: item.name,
      component: comp,
      meta: { ...item.meta },
    })
  }

  return routes
}
