/**
 * Update Tools for Monday.com MCP Server
 * Tools for managing updates/activity: list, create, like, delete, replies
 */

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

// Zod Schemas
const ListUpdatesSchema = z.object({
  item_id: z.string().describe("Item ID"),
  limit: z.number().min(1).max(100).optional().describe("Number of updates to return"),
  page: z.number().min(1).optional().describe("Page number for pagination"),
});

const GetUpdateSchema = z.object({
  update_id: z.string().describe("Update ID"),
});

const CreateUpdateSchema = z.object({
  item_id: z.string().describe("Item ID"),
  body: z.string().describe("Update text content (supports HTML)"),
  parent_id: z.string().optional().describe("Parent update ID (for replies)"),
});

const DeleteUpdateSchema = z.object({
  update_id: z.string().describe("Update ID to delete"),
});

const LikeUpdateSchema = z.object({
  update_id: z.string().describe("Update ID to like"),
});

const ListRepliesSchema = z.object({
  update_id: z.string().describe("Parent update ID"),
});

const EditUpdateSchema = z.object({
  update_id: z.string().describe("Update ID to edit"),
  body: z.string().describe("New update text content"),
});

/**
 * Get all update tools
 */
export function getTools(_client: MondayClient): Tool[] {
  return [
    {
      name: "monday_list_updates",
      description: "List all updates (comments/activity) for an item. Returns updates in reverse chronological order.",
      inputSchema: {
        type: "object",
        properties: {
          item_id: { type: "string", description: "Item ID" },
          limit: { type: "number", description: "Number of updates to return (default: 25, max: 100)" },
          page: { type: "number", description: "Page number for pagination" },
        },
        required: ["item_id"],
      },
    },
    {
      name: "monday_get_update",
      description: "Get a single update by ID with full details including creator, body, and replies.",
      inputSchema: {
        type: "object",
        properties: {
          update_id: { type: "string", description: "Update ID" },
        },
        required: ["update_id"],
      },
    },
    {
      name: "monday_create_update",
      description: "Create an update (comment) on an item. Supports HTML formatting. Can reply to existing updates by specifying parent_id.",
      inputSchema: {
        type: "object",
        properties: {
          item_id: { type: "string", description: "Item ID" },
          body: { type: "string", description: "Update text content (supports HTML)" },
          parent_id: { type: "string", description: "Parent update ID (for replies)" },
        },
        required: ["item_id", "body"],
      },
    },
    {
      name: "monday_delete_update",
      description: "Delete an update. Only the creator or board admins can delete updates.",
      inputSchema: {
        type: "object",
        properties: {
          update_id: { type: "string", description: "Update ID to delete" },
        },
        required: ["update_id"],
      },
    },
    {
      name: "monday_like_update",
      description: "Like (or unlike if already liked) an update.",
      inputSchema: {
        type: "object",
        properties: {
          update_id: { type: "string", description: "Update ID to like" },
        },
        required: ["update_id"],
      },
    },
    {
      name: "monday_list_replies",
      description: "List all replies to a specific update.",
      inputSchema: {
        type: "object",
        properties: {
          update_id: { type: "string", description: "Parent update ID" },
        },
        required: ["update_id"],
      },
    },
    {
      name: "monday_edit_update",
      description: "Edit the body of an existing update. Only the creator can edit their updates.",
      inputSchema: {
        type: "object",
        properties: {
          update_id: { type: "string", description: "Update ID to edit" },
          body: { type: "string", description: "New update text content" },
        },
        required: ["update_id", "body"],
      },
    },
  ];
}

/**
 * Execute update tool
 */
export async function executeUpdateTool(
  client: MondayClient,
  toolName: string,
  args: any
): Promise<any> {
  switch (toolName) {
    case "monday_list_updates": {
      const params = ListUpdatesSchema.parse(args);
      return await client.getUpdates(params.item_id, params.limit);
    }

    case "monday_get_update": {
      const params = GetUpdateSchema.parse(args);
      const query = `
        query {
          updates(ids: [${params.update_id}]) {
            id
            body
            created_at
            updated_at
            creator_id
            text_body
            item_id
            creator {
              id
              name
              email
            }
            replies {
              id
              body
              created_at
              creator {
                id
                name
              }
            }
          }
        }
      `;
      const result = await (client as any).query(query);
      if (!result.data.updates || result.data.updates.length === 0) {
        throw new Error(`Update ${params.update_id} not found`);
      }
      return result.data.updates[0];
    }

    case "monday_create_update": {
      const params = CreateUpdateSchema.parse(args);
      return await client.createUpdate(params);
    }

    case "monday_delete_update": {
      const params = DeleteUpdateSchema.parse(args);
      const query = `
        mutation {
          delete_update(id: ${params.update_id}) {
            id
          }
        }
      `;
      return await (client as any).query(query);
    }

    case "monday_like_update": {
      const params = LikeUpdateSchema.parse(args);
      const query = `
        mutation {
          like_update(update_id: ${params.update_id}) {
            id
          }
        }
      `;
      return await (client as any).query(query);
    }

    case "monday_list_replies": {
      const params = ListRepliesSchema.parse(args);
      const query = `
        query {
          updates(ids: [${params.update_id}]) {
            replies {
              id
              body
              created_at
              updated_at
              creator_id
              text_body
              creator {
                id
                name
                email
              }
            }
          }
        }
      `;
      const result = await (client as any).query(query);
      if (!result.data.updates || result.data.updates.length === 0) {
        return [];
      }
      return result.data.updates[0].replies || [];
    }

    case "monday_edit_update": {
      const params = EditUpdateSchema.parse(args);
      const query = `
        mutation {
          edit_update(
            id: ${params.update_id}
            body: "${params.body}"
          ) {
            id
            body
            updated_at
          }
        }
      `;
      return await (client as any).query(query);
    }

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