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 registerCreateTag(server: McpServer, env: Env, orgNamespace: string) {
  server.tool(
    toolName("create_tag"),
    "在當前命名空間下建立新的 tag，用於分類工作流與零件。",
    {
      name: z.string().describe("Tag 名稱（在當前 org_namespace 下唯一）"),
      description: z.string().optional().describe("Tag 描述（選填）")
    },
    async ({ name, description }) => {
      try {
        if (!env.KBDB) {
          return { content: [{ type: "text", text: "Error: KBDB service binding unavailable" }], isError: true };
        }
        // Check for duplicate
        const checkResp = await kbdbFetch(env, `/records/search?template=tag&user_id=${encodeURIComponent(orgNamespace)}&name=${encodeURIComponent(name)}`);
        if (checkResp.ok) {
          const checkData = await checkResp.json<{ records: unknown[] }>();
          if (checkData.records && checkData.records.length > 0) {
            return { content: [{ type: "text", text: `Error: Tag '${name}' already exists in this namespace` }], isError: true };
          }
        }
        const recordId = `tag-${orgNamespace}-${name}`;
        const createResp = await kbdbFetch(env, `/records`, {
          method: "POST",
          headers: { "Content-Type": "application/json" },
          body: JSON.stringify({
            template: "tag",
            record_id: recordId,
            user_id: orgNamespace,
            values: { name, description: description ?? "", org_namespace: orgNamespace, created_at: new Date().toISOString() }
          })
        });
        if (!createResp.ok) {
          return { content: [{ type: "text", text: `Error creating 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 };
      }
    }
  );
}
