/**
 * Intercom Tickets Tools
 */

import { z } from 'zod';
import { Tool } from '@modelcontextprotocol/sdk/types.js';
import type { IntercomClient } from '../clients/intercom.js';

// Zod schemas
const CreateTicketSchema = z.object({
  ticket_type_id: z.string(),
  contacts: z.array(z.object({
    id: z.string().optional(),
    external_id: z.string().optional(),
    email: z.string().email().optional(),
  })).optional(),
  ticket_attributes: z.record(z.union([
    z.string(),
    z.number(),
    z.boolean(),
    z.array(z.string()),
  ])).optional(),
});

const UpdateTicketSchema = z.object({
  id: z.string(),
  ticket_type_id: z.string().optional(),
  contacts: z.array(z.object({
    id: z.string().optional(),
    external_id: z.string().optional(),
    email: z.string().email().optional(),
  })).optional(),
  ticket_attributes: z.record(z.union([
    z.string(),
    z.number(),
    z.boolean(),
    z.array(z.string()),
  ])).optional(),
});

const SearchTicketsSchema = z.object({
  query: z.object({
    field: z.string().optional(),
    operator: z.string().optional(),
    value: z.union([z.string(), z.number(), z.boolean(), z.array(z.string())]).optional(),
  }).optional(),
  pagination: z.object({
    per_page: z.number().max(150).optional(),
    starting_after: z.string().optional(),
  }).optional(),
  sort: z.object({
    field: z.string(),
    order: z.enum(['asc', 'desc']),
  }).optional(),
});

// Tool definitions
export function getTools(client: IntercomClient): Array<{
  definition: Tool;
  handler: (args: Record<string, unknown>) => Promise<unknown>;
}> {
  return [
    {
      definition: {
        name: 'intercom_list_tickets',
        description: 'List all tickets with pagination.',
        inputSchema: {
          type: 'object',
          properties: {
            per_page: {
              type: 'number',
              description: 'Number of results per page',
            },
            page: {
              type: 'number',
              description: 'Page number',
            },
          },
        },
      },
      handler: async (args) => {
        const params = args as { per_page?: number; page?: number };
        return client.listTickets(params);
      },
    },

    {
      definition: {
        name: 'intercom_get_ticket',
        description: 'Retrieve a specific ticket by ID.',
        inputSchema: {
          type: 'object',
          properties: {
            id: {
              type: 'string',
              description: 'Ticket ID',
            },
          },
          required: ['id'],
        },
      },
      handler: async (args) => {
        const { id } = args as { id: string };
        return client.getTicket(id as any);
      },
    },

    {
      definition: {
        name: 'intercom_create_ticket',
        description: 'Create a new ticket. Requires ticket_type_id from available ticket types.',
        inputSchema: {
          type: 'object',
          properties: {
            ticket_type_id: {
              type: 'string',
              description: 'Ticket type ID (required) - use list_ticket_types to find available types',
            },
            contacts: {
              type: 'array',
              description: 'Array of contacts to associate with ticket',
              items: {
                type: 'object',
                properties: {
                  id: {
                    type: 'string',
                    description: 'Contact ID',
                  },
                  external_id: {
                    type: 'string',
                    description: 'External contact ID',
                  },
                  email: {
                    type: 'string',
                    description: 'Contact email',
                  },
                },
              },
            },
            ticket_attributes: {
              type: 'object',
              description: 'Custom ticket attributes as key-value pairs',
            },
          },
          required: ['ticket_type_id'],
        },
      },
      handler: async (args) => {
        const data = CreateTicketSchema.parse(args);
        return client.createTicket(data as any);
      },
    },

    {
      definition: {
        name: 'intercom_update_ticket',
        description: 'Update an existing ticket by ID.',
        inputSchema: {
          type: 'object',
          properties: {
            id: {
              type: 'string',
              description: 'Ticket ID',
            },
            ticket_type_id: {
              type: 'string',
              description: 'Ticket type ID',
            },
            contacts: {
              type: 'array',
              description: 'Array of contacts',
              items: {
                type: 'object',
                properties: {
                  id: { type: 'string' },
                  external_id: { type: 'string' },
                  email: { type: 'string' },
                },
              },
            },
            ticket_attributes: {
              type: 'object',
              description: 'Custom ticket attributes',
            },
          },
          required: ['id'],
        },
      },
      handler: async (args) => {
        const { id, ...data } = UpdateTicketSchema.parse(args);
        return client.updateTicket(id as any, data as any);
      },
    },

    {
      definition: {
        name: 'intercom_search_tickets',
        description: 'Search tickets using filters. Supports complex queries.',
        inputSchema: {
          type: 'object',
          properties: {
            query: {
              type: 'object',
              description: 'Filter object',
              properties: {
                field: {
                  type: 'string',
                  description: 'Field to filter on',
                },
                operator: {
                  type: 'string',
                  enum: ['=', '!=', 'IN', 'NIN', '>', '<', '>=', '<='],
                },
                value: {
                  description: 'Value to filter by',
                },
              },
            },
            pagination: {
              type: 'object',
              properties: {
                per_page: { type: 'number', maximum: 150 },
                starting_after: { type: 'string' },
              },
            },
            sort: {
              type: 'object',
              properties: {
                field: { type: 'string' },
                order: { type: 'string', enum: ['asc', 'desc'] },
              },
              required: ['field', 'order'],
            },
          },
        },
      },
      handler: async (args) => {
        const data = SearchTicketsSchema.parse(args);
        return client.searchTickets(data as any);
      },
    },

    {
      definition: {
        name: 'intercom_list_ticket_types',
        description: 'List all available ticket types in your workspace. Use these IDs when creating tickets.',
        inputSchema: {
          type: 'object',
          properties: {},
        },
      },
      handler: async () => {
        return client.listTicketTypes();
      },
    },

    {
      definition: {
        name: 'intercom_get_ticket_type',
        description: 'Retrieve a specific ticket type by ID, including all custom attributes.',
        inputSchema: {
          type: 'object',
          properties: {
            id: {
              type: 'string',
              description: 'Ticket type ID',
            },
          },
          required: ['id'],
        },
      },
      handler: async (args) => {
        const { id } = args as { id: string };
        return client.getTicketType(id as any);
      },
    },
  ];
}
