/**
 * Webhook Tools for Monday.com MCP Server
 * Tools for managing webhooks: create, delete
 */

import { z } from "zod";
import { Tool } from "@modelcontextprotocol/sdk/types.js";
import { MondayClient } from "../clients/monday.js";

// Zod Schemas
const CreateWebhookSchema = z.object({
  board_id: z.string().describe("Board ID to create webhook for"),
  url: z.string().url().describe("Webhook URL to receive events"),
  event: z.enum([
    "create_item",
    "change_column_value",
    "change_status_column_value",
    "change_specific_column_value",
    "create_update",
    "delete_update",
    "item_archived",
    "item_deleted",
    "item_moved_to_group",
    "item_restored",
    "subitem_created",
  ]).describe("Event type to subscribe to"),
  config: z.record(z.any()).optional().describe("Optional webhook configuration (e.g., column_id for specific column events)"),
});

const DeleteWebhookSchema = z.object({
  webhook_id: z.string().describe("Webhook ID to delete"),
});

const ListWebhooksSchema = z.object({
  board_id: z.string().describe("Board ID to list webhooks for"),
});

/**
 * Get all webhook tools
 */
export function getTools(_client: MondayClient): Tool[] {
  return [
    {
      name: "monday_create_webhook",
      description: "Create a webhook to receive real-time events from a board. Events include item creation, column changes, updates, etc. The URL will receive POST requests with event data.",
      inputSchema: {
        type: "object",
        properties: {
          board_id: { type: "string", description: "Board ID to create webhook for" },
          url: { type: "string", description: "Webhook URL to receive events (must be HTTPS)" },
          event: {
            type: "string",
            enum: [
              "create_item",
              "change_column_value",
              "change_status_column_value",
              "change_specific_column_value",
              "create_update",
              "delete_update",
              "item_archived",
              "item_deleted",
              "item_moved_to_group",
              "item_restored",
              "subitem_created",
            ],
            description: "Event type to subscribe to",
          },
          config: { type: "object", description: "Optional webhook configuration (e.g., {column_id: 'status'} for specific column)" },
        },
        required: ["board_id", "url", "event"],
      },
    },
    {
      name: "monday_delete_webhook",
      description: "Delete a webhook. The webhook will stop receiving events immediately.",
      inputSchema: {
        type: "object",
        properties: {
          webhook_id: { type: "string", description: "Webhook ID to delete" },
        },
        required: ["webhook_id"],
      },
    },
    {
      name: "monday_list_webhooks",
      description: "List all webhooks for a board.",
      inputSchema: {
        type: "object",
        properties: {
          board_id: { type: "string", description: "Board ID to list webhooks for" },
        },
        required: ["board_id"],
      },
    },
  ];
}

/**
 * Execute webhook tool
 */
export async function executeWebhookTool(
  client: MondayClient,
  toolName: string,
  args: any
): Promise<any> {
  switch (toolName) {
    case "monday_create_webhook": {
      const params = CreateWebhookSchema.parse(args);
      return await client.createWebhook(params);
    }

    case "monday_delete_webhook": {
      const params = DeleteWebhookSchema.parse(args);
      return await client.deleteWebhook(params.webhook_id);
    }

    case "monday_list_webhooks": {
      const params = ListWebhooksSchema.parse(args);
      const query = `
        query {
          boards(ids: [${params.board_id}]) {
            webhooks {
              id
              board_id
              url
              event
              config
            }
          }
        }
      `;
      const result = await (client as any).query(query);
      if (!result.data.boards || result.data.boards.length === 0) {
        return [];
      }
      return result.data.boards[0].webhooks || [];
    }

    default:
      throw new Error(`Unknown webhook tool: ${toolName}`);
  }
}
