/**
 * Automation Tools for Monday.com MCP Server
 * Tools for managing automations: list
 */

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

// Zod Schemas
const ListAutomationsSchema = z.object({
  board_id: z.string().describe("Board ID to list automations for"),
});

const GetAutomationSchema = z.object({
  automation_id: z.string().describe("Automation ID"),
});

/**
 * Get all automation tools
 */
export function getTools(_client: MondayClient): Tool[] {
  return [
    {
      name: "monday_list_automations",
      description: "List all automations configured for a board. Automations are workflow rules that trigger actions based on events.",
      inputSchema: {
        type: "object",
        properties: {
          board_id: { type: "string", description: "Board ID to list automations for" },
        },
        required: ["board_id"],
      },
    },
    {
      name: "monday_get_automation",
      description: "Get details for a specific automation by ID.",
      inputSchema: {
        type: "object",
        properties: {
          automation_id: { type: "string", description: "Automation ID" },
        },
        required: ["automation_id"],
      },
    },
  ];
}

/**
 * Execute automation tool
 */
export async function executeAutomationTool(
  client: MondayClient,
  toolName: string,
  args: any
): Promise<any> {
  switch (toolName) {
    case "monday_list_automations": {
      const params = ListAutomationsSchema.parse(args);
      const query = `
        query {
          boards(ids: [${params.board_id}]) {
            automations {
              id
              name
              enabled
            }
          }
        }
      `;
      const result = await (client as any).query(query);
      if (!result.data.boards || result.data.boards.length === 0) {
        return [];
      }
      return result.data.boards[0].automations || [];
    }

    case "monday_get_automation": {
      const params = GetAutomationSchema.parse(args);
      const query = `
        query {
          automations(ids: [${params.automation_id}]) {
            id
            name
            enabled
          }
        }
      `;
      const result = await (client as any).query(query);
      if (!result.data.automations || result.data.automations.length === 0) {
        throw new Error(`Automation ${params.automation_id} not found`);
      }
      return result.data.automations[0];
    }

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