import { describe, expect, it, vi } from 'vitest';

import { createMcpToolLoader } from './mcpToolLoader';

describe('createMcpToolLoader', () => {
  it('复用同一 MCP 的并发请求和已完成结果', async () => {
    const request = vi.fn(async (id: string) => ({ id, tools: ['search'] }));
    const load = createMcpToolLoader(request);

    const [first, second] = await Promise.all([load('mcp-1'), load('mcp-1')]);
    const third = await load('mcp-1');

    expect(request).toHaveBeenCalledTimes(1);
    expect(first).toEqual({ id: 'mcp-1', tools: ['search'] });
    expect(second).toBe(first);
    expect(third).toBe(first);
  });

  it('分别加载不同的 MCP', async () => {
    const request = vi.fn(async (id: string) => ({ id }));
    const load = createMcpToolLoader(request);

    await Promise.all([load('mcp-1'), load('mcp-2')]);

    expect(request).toHaveBeenCalledTimes(2);
  });

  it('请求失败后允许重新加载', async () => {
    const request = vi
      .fn<(id: string) => Promise<undefined | { id: string }>>()
      .mockRejectedValueOnce(new Error('network error'))
      .mockResolvedValueOnce({ id: 'mcp-1' });
    const load = createMcpToolLoader(request);

    await expect(load('mcp-1')).rejects.toThrow('network error');
    await expect(load('mcp-1')).resolves.toEqual({ id: 'mcp-1' });
    expect(request).toHaveBeenCalledTimes(2);
  });
});
