/**
 * Folder Tools for Monday.com MCP Server
 * Tools for managing folders: list, create, update
 */

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

// Zod Schemas
const ListFoldersSchema = z.object({
  workspace_id: z.string().describe("Workspace ID"),
});

const GetFolderSchema = z.object({
  folder_id: z.string().describe("Folder ID"),
});

const CreateFolderSchema = z.object({
  workspace_id: z.string().describe("Workspace ID to create folder in"),
  name: z.string().describe("Folder name"),
  color: z.string().optional().describe("Folder color (hex code)"),
  parent_folder_id: z.string().optional().describe("Parent folder ID for nested folders"),
});

const UpdateFolderSchema = z.object({
  folder_id: z.string().describe("Folder ID to update"),
  name: z.string().optional().describe("New folder name"),
  color: z.string().optional().describe("New folder color (hex code)"),
});

const DeleteFolderSchema = z.object({
  folder_id: z.string().describe("Folder ID to delete"),
});

/**
 * Get all folder tools
 */
export function getTools(_client: MondayClient): Tool[] {
  return [
    {
      name: "monday_list_folders",
      description: "List all folders in a workspace. Folders organize boards within a workspace.",
      inputSchema: {
        type: "object",
        properties: {
          workspace_id: { type: "string", description: "Workspace ID" },
        },
        required: ["workspace_id"],
      },
    },
    {
      name: "monday_get_folder",
      description: "Get a single folder by ID with details including child folders and boards.",
      inputSchema: {
        type: "object",
        properties: {
          folder_id: { type: "string", description: "Folder ID" },
        },
        required: ["folder_id"],
      },
    },
    {
      name: "monday_create_folder",
      description: "Create a new folder in a workspace. Optionally specify a parent folder for nesting.",
      inputSchema: {
        type: "object",
        properties: {
          workspace_id: { type: "string", description: "Workspace ID to create folder in" },
          name: { type: "string", description: "Folder name" },
          color: { type: "string", description: "Folder color (hex code)" },
          parent_folder_id: { type: "string", description: "Parent folder ID for nested folders" },
        },
        required: ["workspace_id", "name"],
      },
    },
    {
      name: "monday_update_folder",
      description: "Update a folder's name or color.",
      inputSchema: {
        type: "object",
        properties: {
          folder_id: { type: "string", description: "Folder ID to update" },
          name: { type: "string", description: "New folder name" },
          color: { type: "string", description: "New folder color (hex code)" },
        },
        required: ["folder_id"],
      },
    },
    {
      name: "monday_delete_folder",
      description: "Delete a folder. Boards inside the folder will be moved to the workspace root.",
      inputSchema: {
        type: "object",
        properties: {
          folder_id: { type: "string", description: "Folder ID to delete" },
        },
        required: ["folder_id"],
      },
    },
  ];
}

/**
 * Execute folder tool
 */
export async function executeFolderTool(
  client: MondayClient,
  toolName: string,
  args: any
): Promise<any> {
  switch (toolName) {
    case "monday_list_folders": {
      const params = ListFoldersSchema.parse(args);
      const query = `
        query {
          workspaces(ids: [${params.workspace_id}]) {
            folders {
              id
              name
              color
              children {
                id
                name
                color
              }
            }
          }
        }
      `;
      const result = await (client as any).query(query);
      if (!result.data.workspaces || result.data.workspaces.length === 0) {
        return [];
      }
      return result.data.workspaces[0].folders || [];
    }

    case "monday_get_folder": {
      const params = GetFolderSchema.parse(args);
      const query = `
        query {
          folders(ids: [${params.folder_id}]) {
            id
            name
            color
            workspace_id
            parent_id
            children {
              id
              name
              color
            }
          }
        }
      `;
      const result = await (client as any).query(query);
      if (!result.data.folders || result.data.folders.length === 0) {
        throw new Error(`Folder ${params.folder_id} not found`);
      }
      return result.data.folders[0];
    }

    case "monday_create_folder": {
      const params = CreateFolderSchema.parse(args);
      let mutationArgs = [
        `workspace_id: ${params.workspace_id}`,
        `name: "${params.name}"`,
      ];
      if (params.color) {
        mutationArgs.push(`color: "${params.color}"`);
      }
      if (params.parent_folder_id) {
        mutationArgs.push(`parent_folder_id: ${params.parent_folder_id}`);
      }

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

    case "monday_update_folder": {
      const params = UpdateFolderSchema.parse(args);
      if (!params.name && !params.color) {
        throw new Error("At least one of name or color must be provided");
      }

      let mutationArgs = [`folder_id: ${params.folder_id}`];
      if (params.name) {
        mutationArgs.push(`name: "${params.name}"`);
      }
      if (params.color) {
        mutationArgs.push(`color: "${params.color}"`);
      }

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

    case "monday_delete_folder": {
      const params = DeleteFolderSchema.parse(args);
      const query = `
        mutation {
          delete_folder(folder_id: ${params.folder_id}) {
            id
          }
        }
      `;
      return await (client as any).query(query);
    }

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