type McpToolRequester<T> = (id: string) => Promise<T | undefined>;

/**
 * 创建页面级 MCP 工具加载器，同一 MCP 在页面生命周期内只请求一次。
 */
export function createMcpToolLoader<T>(request: McpToolRequester<T>) {
  const requests = new Map<string, Promise<T | undefined>>();

  return function loadMcpTools(id: number | string) {
    const key = String(id || '').trim();
    if (!key) {
      return Promise.resolve(undefined);
    }

    const cached = requests.get(key);
    if (cached) {
      return cached;
    }

    const pending = request(key).then(
      (result) => {
        if (result === undefined) {
          requests.delete(key);
        }
        return result;
      },
      (error) => {
        requests.delete(key);
        throw error;
      },
    );
    requests.set(key, pending);
    return pending;
  };
}
