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

export function registerDeleteTag(server: McpServer, env: Env, orgNamespace: string) {
  server.tool(
    toolName("delete_tag"),
    "刪除當前命名空間下的指定 tag。",
    { tag_name: z.string().describe("要刪除的 Tag 名稱") },
    async ({ tag_name }) => {
      try {
        if (!env.KBDB) {
          return { content: [{ type: "text", text: "Error: KBDB service binding unavailable" }], isError: true };
        }
        const recordId = `tag-${orgNamespace}-${tag_name}`;
        const deleteResp = await kbdbFetch(env, `/records/${encodeURIComponent(recordId)}`, { method: "DELETE" });
        if (deleteResp.status === 404) {
          return { content: [{ type: "text", text: `Error: Tag '${tag_name}' not found` }], isError: true };
        }
        if (!deleteResp.ok) {
          return { content: [{ type: "text", text: `Error deleting tag: ${await deleteResp.text()}` }], isError: true };
        }
        return { content: [{ type: "text", text: `Tag '${tag_name}' deleted successfully` }] };
      } catch (error) {
        return { content: [{ type: "text", text: `Internal Error: ${error instanceof Error ? error.message : String(error)}` }], isError: true };
      }
    }
  );
}
