/**
 * Column Tools for Monday.com MCP Server
 * Tools for managing columns: list, create, update, delete, change value
 */

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

// Zod Schemas
const ListColumnsSchema = z.object({
  board_id: z.string().describe("Board ID"),
});

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

const CreateColumnSchema = z.object({
  board_id: z.string().describe("Board ID"),
  title: z.string().describe("Column title"),
  column_type: z.string().describe("Column type (e.g., text, status, date, people, numbers)"),
  description: z.string().optional().describe("Column description"),
  defaults: z.record(z.any()).optional().describe("Default values for the column"),
});

const UpdateColumnSchema = z.object({
  board_id: z.string().describe("Board ID"),
  column_id: z.string().describe("Column ID to update"),
  title: z.string().optional().describe("New column title"),
  description: z.string().optional().describe("New column description"),
});

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

const ChangeColumnValueSchema = z.object({
  board_id: z.string().describe("Board ID"),
  item_id: z.string().describe("Item ID"),
  column_id: z.string().describe("Column ID"),
  value: z.any().describe("New value (format depends on column type)"),
});

const ChangeSimpleColumnValueSchema = z.object({
  board_id: z.string().describe("Board ID"),
  item_id: z.string().describe("Item ID"),
  column_id: z.string().describe("Column ID"),
  value: z.string().describe("Simple string value"),
  create_labels_if_missing: z.boolean().optional().describe("Create labels if they don't exist"),
});

const ChangeMultipleColumnValuesSchema = z.object({
  board_id: z.string().describe("Board ID"),
  item_id: z.string().describe("Item ID"),
  column_values: z.record(z.any()).describe("Column values to update (keys are column IDs)"),
  create_labels_if_missing: z.boolean().optional().describe("Create labels if they don't exist"),
});

/**
 * Get all column tools
 */
export function getTools(_client: MondayClient): Tool[] {
  return [
    {
      name: "monday_list_columns",
      description: "List all columns in a board with their IDs, titles, types, and settings.",
      inputSchema: {
        type: "object",
        properties: {
          board_id: { type: "string", description: "Board ID" },
        },
        required: ["board_id"],
      },
    },
    {
      name: "monday_get_column",
      description: "Get details for a specific column including its type, settings, and configuration.",
      inputSchema: {
        type: "object",
        properties: {
          board_id: { type: "string", description: "Board ID" },
          column_id: { type: "string", description: "Column ID" },
        },
        required: ["board_id", "column_id"],
      },
    },
    {
      name: "monday_create_column",
      description: "Create a new column in a board. Specify column type (text, status, date, people, numbers, etc.) and optional defaults.",
      inputSchema: {
        type: "object",
        properties: {
          board_id: { type: "string", description: "Board ID" },
          title: { type: "string", description: "Column title" },
          column_type: { type: "string", description: "Column type (text, status, date, people, numbers, etc.)" },
          description: { type: "string", description: "Column description" },
          defaults: { type: "object", description: "Default values/settings for the column" },
        },
        required: ["board_id", "title", "column_type"],
      },
    },
    {
      name: "monday_update_column",
      description: "Update a column's title or description.",
      inputSchema: {
        type: "object",
        properties: {
          board_id: { type: "string", description: "Board ID" },
          column_id: { type: "string", description: "Column ID to update" },
          title: { type: "string", description: "New column title" },
          description: { type: "string", description: "New column description" },
        },
        required: ["board_id", "column_id"],
      },
    },
    {
      name: "monday_delete_column",
      description: "Delete a column from a board. This will remove the column and all its values from all items.",
      inputSchema: {
        type: "object",
        properties: {
          board_id: { type: "string", description: "Board ID" },
          column_id: { type: "string", description: "Column ID to delete" },
        },
        required: ["board_id", "column_id"],
      },
    },
    {
      name: "monday_change_column_value",
      description: "Change a column value for an item. Value format depends on column type (e.g., {text: 'value'} for text, {index: 0} for status).",
      inputSchema: {
        type: "object",
        properties: {
          board_id: { type: "string", description: "Board ID" },
          item_id: { type: "string", description: "Item ID" },
          column_id: { type: "string", description: "Column ID" },
          value: { type: "object", description: "New value (format depends on column type)" },
        },
        required: ["board_id", "item_id", "column_id", "value"],
      },
    },
    {
      name: "monday_change_simple_column_value",
      description: "Change a simple text column value using a string. Easier than the full change_column_value for basic text columns.",
      inputSchema: {
        type: "object",
        properties: {
          board_id: { type: "string", description: "Board ID" },
          item_id: { type: "string", description: "Item ID" },
          column_id: { type: "string", description: "Column ID" },
          value: { type: "string", description: "Simple string value" },
          create_labels_if_missing: { type: "boolean", description: "Create labels if they don't exist" },
        },
        required: ["board_id", "item_id", "column_id", "value"],
      },
    },
    {
      name: "monday_change_multiple_column_values",
      description: "Change multiple column values for an item in a single request. More efficient than changing values one by one.",
      inputSchema: {
        type: "object",
        properties: {
          board_id: { type: "string", description: "Board ID" },
          item_id: { type: "string", description: "Item ID" },
          column_values: { type: "object", description: "Column values to update (keys are column IDs)" },
          create_labels_if_missing: { type: "boolean", description: "Create labels if they don't exist" },
        },
        required: ["board_id", "item_id", "column_values"],
      },
    },
  ];
}

/**
 * Execute column tool
 */
export async function executeColumnTool(
  client: MondayClient,
  toolName: string,
  args: any
): Promise<any> {
  switch (toolName) {
    case "monday_list_columns": {
      const params = ListColumnsSchema.parse(args);
      const board = await client.getBoard(params.board_id);
      return board.columns || [];
    }

    case "monday_get_column": {
      const params = GetColumnSchema.parse(args);
      const board = await client.getBoard(params.board_id);
      const column = board.columns?.find((c) => c.id === params.column_id);
      if (!column) {
        throw new Error(`Column ${params.column_id} not found in board ${params.board_id}`);
      }
      return column;
    }

    case "monday_create_column": {
      const params = CreateColumnSchema.parse(args);
      let mutationArgs = [
        `board_id: ${params.board_id}`,
        `title: "${params.title}"`,
        `column_type: ${params.column_type}`,
      ];
      if (params.description) {
        mutationArgs.push(`description: "${params.description}"`);
      }
      if (params.defaults) {
        const jsonValue = JSON.stringify(JSON.stringify(params.defaults));
        mutationArgs.push(`defaults: ${jsonValue}`);
      }

      const query = `
        mutation {
          create_column(${mutationArgs.join(", ")}) {
            id
            title
            type
            description
            settings_str
          }
        }
      `;
      return await (client as any).query(query);
    }

    case "monday_update_column": {
      const params = UpdateColumnSchema.parse(args);
      if (!params.title && !params.description) {
        throw new Error("At least one of title or description must be provided");
      }

      let mutationArgs = [`board_id: ${params.board_id}`, `column_id: "${params.column_id}"`];
      if (params.title) {
        mutationArgs.push(`title: "${params.title}"`);
      }
      if (params.description !== undefined) {
        mutationArgs.push(`description: "${params.description}"`);
      }

      const query = `
        mutation {
          change_column_metadata(${mutationArgs.join(", ")}) {
            id
            title
            description
          }
        }
      `;
      return await (client as any).query(query);
    }

    case "monday_delete_column": {
      const params = DeleteColumnSchema.parse(args);
      const query = `
        mutation {
          delete_column(
            board_id: ${params.board_id}
            column_id: "${params.column_id}"
          ) {
            id
          }
        }
      `;
      return await (client as any).query(query);
    }

    case "monday_change_column_value": {
      const params = ChangeColumnValueSchema.parse(args);
      return await client.changeColumnValue({
        board_id: params.board_id,
        item_id: params.item_id,
        column_id: params.column_id,
        value: params.value,
      });
    }

    case "monday_change_simple_column_value": {
      const params = ChangeSimpleColumnValueSchema.parse(args);
      let mutationArgs = [
        `board_id: ${params.board_id}`,
        `item_id: ${params.item_id}`,
        `column_id: "${params.column_id}"`,
        `value: "${params.value}"`,
      ];
      if (params.create_labels_if_missing !== undefined) {
        mutationArgs.push(`create_labels_if_missing: ${params.create_labels_if_missing}`);
      }

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

    case "monday_change_multiple_column_values": {
      const params = ChangeMultipleColumnValuesSchema.parse(args);
      const jsonValue = JSON.stringify(JSON.stringify(params.column_values));
      let mutationArgs = [
        `board_id: ${params.board_id}`,
        `item_id: ${params.item_id}`,
        `column_values: ${jsonValue}`,
      ];
      if (params.create_labels_if_missing !== undefined) {
        mutationArgs.push(`create_labels_if_missing: ${params.create_labels_if_missing}`);
      }

      const query = `
        mutation {
          change_multiple_column_values(${mutationArgs.join(", ")}) {
            id
            name
            column_values {
              id
              text
              value
            }
          }
        }
      `;
      return await (client as any).query(query);
    }

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