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 registerUntagResource(server: McpServer, env: Env, orgNamespace: string) {
  server.tool(
    toolName("untag_resource"),
    "移除當前命名空間下工作流或零件的 tag 標籤。",
    {
      resource_type: z.enum(["workflow", "component"]).describe("資源類型：workflow 或 component"),
      resource_id: z.string().describe("資源 ID"),
      tag_name: z.string().describe("要移除的 tag 名稱")
    },
    async ({ resource_type, resource_id, tag_name }) => {
      try {
        if (!env.KBDB) {
          return { content: [{ type: "text", text: "Error: KBDB service binding unavailable" }], isError: true };
        }
        const recordId = `rt-${resource_type}-${resource_id}-${tag_name}`;
        const getResp = await kbdbFetch(env, `/records/${recordId}`);
        if (getResp.status === 404) {
          return { content: [{ type: "text", text: "Error: Resource tag association not found" }], isError: true };
        }
        if (!getResp.ok) {
          return { content: [{ type: "text", text: "Error: KBDB service unavailable" }], isError: true };
        }
        const record = await getResp.json<{ slots: { org_namespace: string } }>();
        if (!record.slots || record.slots.org_namespace !== orgNamespace) {
          return { content: [{ type: "text", text: "Error: Resource tag association not found" }], isError: true };
        }
        const deleteResp = await kbdbFetch(env, `/records/${recordId}`, { method: "DELETE" });
        if (!deleteResp.ok) {
          return { content: [{ type: "text", text: "Error: KBDB service unavailable" }], isError: true };
        }
        return { content: [{ type: "text", text: `Tag '${tag_name}' removed from ${resource_type} '${resource_id}' successfully` }] };
      } catch (error) {
        return { content: [{ type: "text", text: `Internal Error: ${error instanceof Error ? error.message : String(error)}` }], isError: true };
      }
    }
  );
}
