import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
import { toolName } from "../brand.js";
import { Env } from "../types.js";
import { kbdbFetch } from "../lib/kbdb-client.js";

export function registerListTags(server: McpServer, env: Env, orgNamespace: string) {
  server.tool(
    toolName("list_tags"),
    "列出當前命名空間下所有的 tag。",
    {},
    async () => {
      try {
        if (!env.KBDB) {
          return { content: [{ type: "text", text: "Error: KBDB service binding unavailable" }], isError: true };
        }
        const resp = await kbdbFetch(env, `/records/search?template=tag&user_id=${encodeURIComponent(orgNamespace)}`);
        if (!resp.ok) {
          return { content: [{ type: "text", text: `Error fetching tags: ${await resp.text()}` }], isError: true };
        }
        const data = await resp.json<{ records: unknown[] }>();
        return { content: [{ type: "text", text: JSON.stringify(data.records, null, 2) }] };
      } catch (error) {
        return { content: [{ type: "text", text: `Internal Error: ${error instanceof Error ? error.message : String(error)}` }], isError: true };
      }
    }
  );
}
