import type { MenuDataItem } from '@ant-design/pro-components';
import * as Icons from '@ant-design/icons';
import type { MenuItem } from '@/api/types/menu';
import { createElement, type ComponentType, type ReactNode } from 'react';

function resolveIcon(name?: string): ReactNode {
  if (!name) return undefined;

  // @ant-design/icons 同时导出组件和工具函数（如 setTwoToneColor），不能直接断言为 ComponentType
  const Candidate = (Icons as unknown as Record<string, unknown>)[name];
  if (Candidate === undefined) return undefined;

  if (typeof Candidate !== 'function' && typeof Candidate !== 'object') return undefined;

  return createElement(Candidate as ComponentType);
}

/** 后端菜单树 → ProLayout route */
export function menusToProRoutes(menus: MenuItem[]): MenuDataItem[] {
  return menus.map(m => ({
    path: m.path,
    name: m.name,
    icon: resolveIcon(m.icon),
    children: m.children?.length ? menusToProRoutes(m.children) : undefined,
  }));
}
