/**
 * User Tools for Monday.com MCP Server
 * Tools for managing users: list, get
 */

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

// Zod Schemas
const ListUsersSchema = z.object({
  limit: z.number().min(1).max(100).optional().describe("Number of users to return"),
  page: z.number().min(1).optional().describe("Page number for pagination"),
  kind: z.enum(["all", "non_guests", "guests", "non_pending"]).optional().describe("Filter by user type"),
  newest_first: z.boolean().optional().describe("Sort by newest first"),
  non_active: z.boolean().optional().describe("Include non-active users"),
});

const GetUserSchema = z.object({
  user_id: z.string().describe("User ID"),
});

const GetCurrentUserSchema = z.object({});

/**
 * Get all user tools
 */
export function getTools(_client: MondayClient): Tool[] {
  return [
    {
      name: "monday_list_users",
      description: "List all users in the account with their details (name, email, role, teams). Can filter by user type (all/non_guests/guests/non_pending).",
      inputSchema: {
        type: "object",
        properties: {
          limit: { type: "number", description: "Number of users to return (default: 50, max: 100)" },
          page: { type: "number", description: "Page number for pagination" },
          kind: { type: "string", enum: ["all", "non_guests", "guests", "non_pending"], description: "Filter by user type" },
          newest_first: { type: "boolean", description: "Sort by newest first" },
          non_active: { type: "boolean", description: "Include non-active users" },
        },
      },
    },
    {
      name: "monday_get_user",
      description: "Get a single user by ID with full details including teams, phone, location, timezone, and account info.",
      inputSchema: {
        type: "object",
        properties: {
          user_id: { type: "string", description: "User ID" },
        },
        required: ["user_id"],
      },
    },
    {
      name: "monday_get_current_user",
      description: "Get the currently authenticated user's details.",
      inputSchema: {
        type: "object",
        properties: {},
      },
    },
  ];
}

/**
 * Execute user tool
 */
export async function executeUserTool(
  client: MondayClient,
  toolName: string,
  args: any
): Promise<any> {
  switch (toolName) {
    case "monday_list_users": {
      const params = ListUsersSchema.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}`);
      if (params.newest_first !== undefined) queryArgs.push(`newest_first: ${params.newest_first}`);
      if (params.non_active !== undefined) queryArgs.push(`non_active: ${params.non_active}`);

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

      const query = `
        query {
          users${argsStr} {
            id
            name
            email
            url
            photo_thumb
            photo_original
            is_guest
            is_pending
            enabled
            created_at
            title
            phone
            mobile_phone
            location
            time_zone_identifier
            birthday
            country_code
            teams {
              id
              name
            }
          }
        }
      `;
      const result = await (client as any).query(query);
      return result.data.users || [];
    }

    case "monday_get_user": {
      const params = GetUserSchema.parse(args);
      const query = `
        query {
          users(ids: [${params.user_id}]) {
            id
            name
            email
            url
            photo_thumb
            photo_original
            photo_tiny
            is_guest
            is_pending
            enabled
            created_at
            title
            phone
            mobile_phone
            location
            time_zone_identifier
            birthday
            country_code
            teams {
              id
              name
              picture_url
            }
            account {
              id
              name
              slug
              tier
            }
          }
        }
      `;
      const result = await (client as any).query(query);
      if (!result.data.users || result.data.users.length === 0) {
        throw new Error(`User ${params.user_id} not found`);
      }
      return result.data.users[0];
    }

    case "monday_get_current_user": {
      GetCurrentUserSchema.parse(args);
      const query = `
        query {
          me {
            id
            name
            email
            url
            photo_thumb
            photo_original
            is_guest
            enabled
            created_at
            title
            phone
            location
            time_zone_identifier
            birthday
            teams {
              id
              name
            }
            account {
              id
              name
              slug
              tier
            }
          }
        }
      `;
      const result = await (client as any).query(query);
      return result.data.me;
    }

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