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 registerTagResource(server: McpServer, env: Env, orgNamespace: string) {
  server.tool(
    toolName("tag_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 tagResp = await kbdbFetch(env, `/records/search?template=tag&user_id=${encodeURIComponent(orgNamespace)}&name=${encodeURIComponent(tag_name)}`);
        if (!tagResp.ok) {
          return { content: [{ type: "text", text: "Error: KBDB service unavailable" }], isError: true };
        }
        const tagData = await tagResp.json<{ records: unknown[] }>();
        if (!tagData.records || tagData.records.length === 0) {
          return { content: [{ type: "text", text: `Error: Tag not found` }], isError: true };
        }
        const prefix = resource_type === "workflow" ? "wf" : "comp";
        const resourceResp = await kbdbFetch(env, `/records/${prefix}-${resource_id}`);
        if (!resourceResp.ok) {
          return { content: [{ type: "text", text: `Error: Resource not found` }], isError: true };
        }
        const resourceData = await resourceResp.json<{ slots: { org_namespace: string } }>();
        if (!resourceData.slots || resourceData.slots.org_namespace !== orgNamespace) {
          return { content: [{ type: "text", text: `Error: Resource not found` }], isError: true };
        }
        const recordId = `rt-${resource_type}-${resource_id}-${tag_name}`;
        const createResp = await kbdbFetch(env, `/records`, {
          method: "POST",
          headers: { "Content-Type": "application/json" },
          body: JSON.stringify({
            template: "resource_tag",
            record_id: recordId,
            user_id: orgNamespace,
            values: { resource_type, resource_id, tag_name, org_namespace: orgNamespace }
          })
        });
        if (!createResp.ok) {
          return { content: [{ type: "text", text: `Error creating resource_tag: ${await createResp.text()}` }], isError: true };
        }
        return { content: [{ type: "text", text: JSON.stringify(await createResp.json(), null, 2) }] };
      } catch (error) {
        return { content: [{ type: "text", text: `Internal Error: ${error instanceof Error ? error.message : String(error)}` }], isError: true };
      }
    }
  );
}
