/**
 * Workspace Tools for Monday.com MCP Server
 * Tools for managing workspaces: list, get, create
 */

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

// Zod Schemas
const ListWorkspacesSchema = z.object({
  limit: z.number().min(1).max(100).optional().describe("Number of workspaces to return"),
  page: z.number().min(1).optional().describe("Page number for pagination"),
  kind: z.enum(["open", "closed"]).optional().describe("Filter by workspace type"),
});

const GetWorkspaceSchema = z.object({
  workspace_id: z.string().describe("Workspace ID"),
});

const CreateWorkspaceSchema = z.object({
  name: z.string().describe("Workspace name"),
  kind: z.enum(["open", "closed"]).describe("Workspace type (open or closed)"),
  description: z.string().optional().describe("Workspace description"),
});

/**
 * Get all workspace tools
 */
export function getTools(_client: MondayClient): Tool[] {
  return [
    {
      name: "monday_list_workspaces",
      description: "List all workspaces in the account. Workspaces organize boards and can be open (visible to all) or closed (restricted access).",
      inputSchema: {
        type: "object",
        properties: {
          limit: { type: "number", description: "Number of workspaces to return (default: 50, max: 100)" },
          page: { type: "number", description: "Page number for pagination" },
          kind: { type: "string", enum: ["open", "closed"], description: "Filter by workspace type" },
        },
      },
    },
    {
      name: "monday_get_workspace",
      description: "Get a single workspace by ID with details including subscribers and settings.",
      inputSchema: {
        type: "object",
        properties: {
          workspace_id: { type: "string", description: "Workspace ID" },
        },
        required: ["workspace_id"],
      },
    },
    {
      name: "monday_create_workspace",
      description: "Create a new workspace. Specify whether it's open (visible to all account members) or closed (restricted access).",
      inputSchema: {
        type: "object",
        properties: {
          name: { type: "string", description: "Workspace name" },
          kind: { type: "string", enum: ["open", "closed"], description: "Workspace type" },
          description: { type: "string", description: "Workspace description" },
        },
        required: ["name", "kind"],
      },
    },
  ];
}

/**
 * Execute workspace tool
 */
export async function executeWorkspaceTool(
  client: MondayClient,
  toolName: string,
  args: any
): Promise<any> {
  switch (toolName) {
    case "monday_list_workspaces": {
      const params = ListWorkspacesSchema.parse(args);
      let queryArgs: string[] = [];
      
      if (params.limit !== undefined) queryArgs.push(`limit: ${params.limit}`);
      if (params.page !== undefined) queryArgs.push(`page: ${params.page}`);
      if (params.kind) queryArgs.push(`kind: ${params.kind}`);

      const argsStr = queryArgs.length > 0 ? `(${queryArgs.join(", ")})` : "";

      const query = `
        query {
          workspaces${argsStr} {
            id
            name
            kind
            description
            created_at
            owners_subscribers {
              id
              name
              email
            }
          }
        }
      `;
      const result = await (client as any).query(query);
      return result.data.workspaces || [];
    }

    case "monday_get_workspace": {
      const params = GetWorkspaceSchema.parse(args);
      const query = `
        query {
          workspaces(ids: [${params.workspace_id}]) {
            id
            name
            kind
            description
            created_at
            owners_subscribers {
              id
              name
              email
            }
            teams_subscribers {
              id
              name
            }
            users_subscribers {
              id
              name
              email
            }
          }
        }
      `;
      const result = await (client as any).query(query);
      if (!result.data.workspaces || result.data.workspaces.length === 0) {
        throw new Error(`Workspace ${params.workspace_id} not found`);
      }
      return result.data.workspaces[0];
    }

    case "monday_create_workspace": {
      const params = CreateWorkspaceSchema.parse(args);
      let mutationArgs = [
        `name: "${params.name}"`,
        `kind: ${params.kind}`,
      ];
      if (params.description) {
        mutationArgs.push(`description: "${params.description}"`);
      }

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

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