import test from "node:test";
import assert from "node:assert/strict";
import { createWebSearchTool } from "./web-search.ts";

test("web_search executes metadata-only search through the resolved provider", async () => {
  let resolvedProviderName: string | undefined;

  const tool = createWebSearchTool({
    resolveProvider: async (providerName) => {
      resolvedProviderName = providerName;
      return {
        name: "exa-main",
        type: "exa",
        async search(request) {
          assert.equal(request.query, "exa docs");
          return {
            providerName: "exa-main",
            results: [
              {
                title: "Exa Docs",
                url: "https://exa.ai/docs",
                score: 0.98,
              },
            ],
          };
        },
        async fetch() {
          throw new Error("not used");
        },
      };
    },
  });

  const result = await tool.execute("tool-1", { query: "exa docs" }, undefined, undefined, undefined);

  assert.equal(resolvedProviderName, undefined);
  assert.match((result.content[0] as { text: string }).text, /Exa Docs/);
  assert.equal((result.details as { results: Array<{ url: string }> }).results[0]?.url, "https://exa.ai/docs");
});

test("web_search rejects a blank query before resolving a provider", async () => {
  const tool = createWebSearchTool({
    resolveProvider: async () => {
      throw new Error("should not resolve provider for a blank query");
    },
  });

  await assert.rejects(
    () => tool.execute("tool-1", { query: "   " }, undefined, undefined, undefined),
    /non-empty query/,
  );
});
