/**
 * Board Tools for Monday.com MCP Server
 * Tools for managing boards: list, get, create, update, delete, archive, duplicate
 */

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

// Zod Schemas
const ListBoardsSchema = z.object({
  limit: z.number().min(1).max(100).optional().describe("Number of boards to return (default: 25)"),
  page: z.number().min(1).optional().describe("Page number for pagination (default: 1)"),
  state: z.enum(["active", "archived", "deleted", "all"]).optional().describe("Filter by board state (default: active)"),
  board_kind: z.enum(["public", "private", "share"]).optional().describe("Filter by board type"),
  workspace_ids: z.array(z.string()).optional().describe("Filter by workspace IDs"),
});

const GetBoardSchema = z.object({
  board_id: z.string().describe("Board ID"),
});

const CreateBoardSchema = z.object({
  board_name: z.string().describe("Name of the new board"),
  board_kind: z.enum(["public", "private", "share"]).describe("Board visibility type"),
  description: z.string().optional().describe("Board description"),
  workspace_id: z.string().optional().describe("Workspace ID to create board in"),
  folder_id: z.string().optional().describe("Folder ID to create board in"),
  template_id: z.string().optional().describe("Template ID to use for board creation"),
});

const UpdateBoardSchema = z.object({
  board_id: z.string().describe("Board ID to update"),
  board_attribute: z.enum(["name", "description", "communication"]).describe("Attribute to update"),
  new_value: z.string().describe("New value for the attribute"),
});

const DeleteBoardSchema = z.object({
  board_id: z.string().describe("Board ID to delete"),
});

const ArchiveBoardSchema = z.object({
  board_id: z.string().describe("Board ID to archive"),
});

const DuplicateBoardSchema = z.object({
  board_id: z.string().describe("Board ID to duplicate"),
  duplicate_type: z.enum(["duplicate_board_with_pulses", "duplicate_board_with_structure"]).describe("Type of duplication"),
  board_name: z.string().optional().describe("Name for the duplicated board"),
  workspace_id: z.string().optional().describe("Workspace ID for the duplicated board"),
  folder_id: z.string().optional().describe("Folder ID for the duplicated board"),
  keep_subscribers: z.boolean().optional().describe("Keep board subscribers in duplicate"),
});

/**
 * Get all board tools
 */
export function getTools(_client: MondayClient): Tool[] {
  return [
    {
      name: "monday_list_boards",
      description: "List all boards in the account. Filter by state (active/archived/deleted), board type (public/private/share), or workspace. Supports pagination.",
      inputSchema: {
        type: "object",
        properties: {
          limit: { type: "number", description: "Number of boards to return (default: 25, max: 100)" },
          page: { type: "number", description: "Page number for pagination (default: 1)" },
          state: { type: "string", enum: ["active", "archived", "deleted", "all"], description: "Filter by board state" },
          board_kind: { type: "string", enum: ["public", "private", "share"], description: "Filter by board type" },
          workspace_ids: { type: "array", items: { type: "string" }, description: "Filter by workspace IDs" },
        },
      },
    },
    {
      name: "monday_get_board",
      description: "Get a single board by ID with full details including columns, groups, and metadata.",
      inputSchema: {
        type: "object",
        properties: {
          board_id: { type: "string", description: "Board ID" },
        },
        required: ["board_id"],
      },
    },
    {
      name: "monday_create_board",
      description: "Create a new board. Can specify board type, workspace, folder, and optionally use a template.",
      inputSchema: {
        type: "object",
        properties: {
          board_name: { type: "string", description: "Name of the new board" },
          board_kind: { type: "string", enum: ["public", "private", "share"], description: "Board visibility type" },
          description: { type: "string", description: "Board description" },
          workspace_id: { type: "string", description: "Workspace ID to create board in" },
          folder_id: { type: "string", description: "Folder ID to create board in" },
          template_id: { type: "string", description: "Template ID to use for board creation" },
        },
        required: ["board_name", "board_kind"],
      },
    },
    {
      name: "monday_update_board",
      description: "Update a board's attributes (name, description, or communication settings).",
      inputSchema: {
        type: "object",
        properties: {
          board_id: { type: "string", description: "Board ID to update" },
          board_attribute: { type: "string", enum: ["name", "description", "communication"], description: "Attribute to update" },
          new_value: { type: "string", description: "New value for the attribute" },
        },
        required: ["board_id", "board_attribute", "new_value"],
      },
    },
    {
      name: "monday_delete_board",
      description: "Permanently delete a board. This action cannot be undone.",
      inputSchema: {
        type: "object",
        properties: {
          board_id: { type: "string", description: "Board ID to delete" },
        },
        required: ["board_id"],
      },
    },
    {
      name: "monday_archive_board",
      description: "Archive a board. Archived boards can be restored later.",
      inputSchema: {
        type: "object",
        properties: {
          board_id: { type: "string", description: "Board ID to archive" },
        },
        required: ["board_id"],
      },
    },
    {
      name: "monday_duplicate_board",
      description: "Duplicate an existing board. Can duplicate with items (pulses) or just the structure (columns and groups).",
      inputSchema: {
        type: "object",
        properties: {
          board_id: { type: "string", description: "Board ID to duplicate" },
          duplicate_type: { type: "string", enum: ["duplicate_board_with_pulses", "duplicate_board_with_structure"], description: "Type of duplication" },
          board_name: { type: "string", description: "Name for the duplicated board" },
          workspace_id: { type: "string", description: "Workspace ID for the duplicated board" },
          folder_id: { type: "string", description: "Folder ID for the duplicated board" },
          keep_subscribers: { type: "boolean", description: "Keep board subscribers in duplicate" },
        },
        required: ["board_id", "duplicate_type"],
      },
    },
  ];
}

/**
 * Execute board tool
 */
export async function executeBoardTool(
  client: MondayClient,
  toolName: string,
  args: any
): Promise<any> {
  switch (toolName) {
    case "monday_list_boards": {
      const params = ListBoardsSchema.parse(args);
      return await client.getBoards(params);
    }

    case "monday_get_board": {
      const params = GetBoardSchema.parse(args);
      return await client.getBoard(params.board_id);
    }

    case "monday_create_board": {
      const params = CreateBoardSchema.parse(args);
      return await client.createBoard(params);
    }

    case "monday_update_board": {
      const params = UpdateBoardSchema.parse(args);
      const query = `
        mutation {
          update_board(
            board_id: ${params.board_id}
            board_attribute: ${params.board_attribute}
            new_value: "${params.new_value}"
          ) {
            id
            name
            description
          }
        }
      `;
      return await (client as any).query(query);
    }

    case "monday_delete_board": {
      const params = DeleteBoardSchema.parse(args);
      const query = `
        mutation {
          delete_board(board_id: ${params.board_id}) {
            id
          }
        }
      `;
      return await (client as any).query(query);
    }

    case "monday_archive_board": {
      const params = ArchiveBoardSchema.parse(args);
      const query = `
        mutation {
          archive_board(board_id: ${params.board_id}) {
            id
            state
          }
        }
      `;
      return await (client as any).query(query);
    }

    case "monday_duplicate_board": {
      const params = DuplicateBoardSchema.parse(args);
      let mutationArgs = [
        `board_id: ${params.board_id}`,
        `duplicate_type: ${params.duplicate_type}`,
      ];
      if (params.board_name) mutationArgs.push(`board_name: "${params.board_name}"`);
      if (params.workspace_id) mutationArgs.push(`workspace_id: ${params.workspace_id}`);
      if (params.folder_id) mutationArgs.push(`folder_id: ${params.folder_id}`);
      if (params.keep_subscribers !== undefined) mutationArgs.push(`keep_subscribers: ${params.keep_subscribers}`);

      const query = `
        mutation {
          duplicate_board(${mutationArgs.join(", ")}) {
            board {
              id
              name
            }
          }
        }
      `;
      return await (client as any).query(query);
    }

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