/**
 * HubSpot Tickets Tools
 * Tools for managing tickets (service/support) in HubSpot CRM
 */

import type { HubSpotClient } from '../clients/hubspot.js';
import type { TicketProperties } from '../types/index.js';

export function getTools(client: HubSpotClient) {
  return [
    {
      name: 'hubspot_list_tickets',
      description: 'List tickets with pagination. Returns up to 100 tickets per request.',
      inputSchema: {
        type: 'object',
        properties: {
          limit: {
            type: 'number',
            description: 'Maximum number of tickets to return (max 100)',
            default: 10,
          },
          after: {
            type: 'string',
            description: 'Pagination cursor from previous response',
          },
          properties: {
            type: 'array',
            items: { type: 'string' },
            description: 'Specific properties to retrieve (e.g., ["subject", "content", "hs_ticket_priority"])',
          },
        },
      },
      handler: async (args: any) => {
        const response = await client.listObjects<TicketProperties>('tickets', {
          limit: Math.min(args.limit || 10, 100),
          after: args.after,
          properties: args.properties,
        });

        return {
          content: [
            {
              type: 'text',
              text: JSON.stringify(
                {
                  total: response.results.length,
                  tickets: response.results,
                  nextCursor: response.paging?.next?.after,
                },
                null,
                2
              ),
            },
          ],
        };
      },
    },

    {
      name: 'hubspot_get_ticket',
      description: 'Get a single ticket by ID with all details',
      inputSchema: {
        type: 'object',
        properties: {
          ticketId: {
            type: 'string',
            description: 'HubSpot ticket ID',
          },
          properties: {
            type: 'array',
            items: { type: 'string' },
            description: 'Specific properties to retrieve',
          },
          associations: {
            type: 'array',
            items: { type: 'string' },
            description: 'Associated object types to include (e.g., ["contacts", "companies"])',
          },
        },
        required: ['ticketId'],
      },
      handler: async (args: any) => {
        const ticket = await client.getObject<TicketProperties>(
          'tickets',
          args.ticketId,
          args.properties,
          args.associations
        );

        return {
          content: [
            {
              type: 'text',
              text: JSON.stringify(ticket, null, 2),
            },
          ],
        };
      },
    },

    {
      name: 'hubspot_create_ticket',
      description: 'Create a new ticket in HubSpot',
      inputSchema: {
        type: 'object',
        properties: {
          subject: {
            type: 'string',
            description: 'Ticket subject (required)',
          },
          content: {
            type: 'string',
            description: 'Ticket content/description',
          },
          hs_ticket_priority: {
            type: 'string',
            description: 'Priority (e.g., "LOW", "MEDIUM", "HIGH")',
          },
          hs_pipeline_stage: {
            type: 'string',
            description: 'Pipeline stage ID',
          },
          hs_pipeline: {
            type: 'string',
            description: 'Pipeline ID',
          },
          hubspot_owner_id: {
            type: 'string',
            description: 'Owner/user ID',
          },
          hs_ticket_category: {
            type: 'string',
            description: 'Ticket category',
          },
          additionalProperties: {
            type: 'object',
            description: 'Additional custom properties as key-value pairs',
          },
        },
        required: ['subject'],
      },
      handler: async (args: any) => {
        const properties: TicketProperties = {
          subject: args.subject,
          content: args.content,
          hs_ticket_priority: args.hs_ticket_priority,
          hs_pipeline_stage: args.hs_pipeline_stage,
          hs_pipeline: args.hs_pipeline,
          hubspot_owner_id: args.hubspot_owner_id,
          hs_ticket_category: args.hs_ticket_category,
          ...(args.additionalProperties || {}),
        };

        // Remove undefined values
        Object.keys(properties).forEach(
          (key) => properties[key] === undefined && delete properties[key]
        );

        const ticket = await client.createObject<TicketProperties>('tickets', properties);

        return {
          content: [
            {
              type: 'text',
              text: JSON.stringify(
                {
                  success: true,
                  ticketId: ticket.id,
                  ticket,
                },
                null,
                2
              ),
            },
          ],
        };
      },
    },

    {
      name: 'hubspot_update_ticket',
      description: 'Update an existing ticket',
      inputSchema: {
        type: 'object',
        properties: {
          ticketId: {
            type: 'string',
            description: 'HubSpot ticket ID',
          },
          subject: {
            type: 'string',
            description: 'Updated subject',
          },
          content: {
            type: 'string',
            description: 'Updated content',
          },
          hs_ticket_priority: {
            type: 'string',
            description: 'Updated priority',
          },
          hs_pipeline_stage: {
            type: 'string',
            description: 'Updated pipeline stage',
          },
          additionalProperties: {
            type: 'object',
            description: 'Additional properties to update as key-value pairs',
          },
        },
        required: ['ticketId'],
      },
      handler: async (args: any) => {
        const properties: Partial<TicketProperties> = {
          subject: args.subject,
          content: args.content,
          hs_ticket_priority: args.hs_ticket_priority,
          hs_pipeline_stage: args.hs_pipeline_stage,
          ...(args.additionalProperties || {}),
        };

        // Remove undefined values
        Object.keys(properties).forEach(
          (key) => properties[key] === undefined && delete properties[key]
        );

        const ticket = await client.updateObject<TicketProperties>(
          'tickets',
          args.ticketId,
          properties
        );

        return {
          content: [
            {
              type: 'text',
              text: JSON.stringify(
                {
                  success: true,
                  ticket,
                },
                null,
                2
              ),
            },
          ],
        };
      },
    },

    {
      name: 'hubspot_delete_ticket',
      description: 'Archive (soft delete) a ticket',
      inputSchema: {
        type: 'object',
        properties: {
          ticketId: {
            type: 'string',
            description: 'HubSpot ticket ID to archive',
          },
        },
        required: ['ticketId'],
      },
      handler: async (args: any) => {
        await client.archiveObject('tickets', args.ticketId);

        return {
          content: [
            {
              type: 'text',
              text: JSON.stringify(
                {
                  success: true,
                  message: `Ticket ${args.ticketId} archived successfully`,
                },
                null,
                2
              ),
            },
          ],
        };
      },
    },

    {
      name: 'hubspot_search_tickets',
      description: 'Search tickets with filters and sorting. Supports complex queries.',
      inputSchema: {
        type: 'object',
        properties: {
          filters: {
            type: 'array',
            items: {
              type: 'object',
              properties: {
                propertyName: { type: 'string' },
                operator: { type: 'string', enum: ['EQ', 'NEQ', 'LT', 'LTE', 'GT', 'GTE', 'CONTAINS_TOKEN', 'HAS_PROPERTY'] },
                value: { type: 'string' },
              },
              required: ['propertyName', 'operator'],
            },
            description: 'Array of filters to apply',
          },
          query: {
            type: 'string',
            description: 'Free text search query',
          },
          sorts: {
            type: 'array',
            items: {
              type: 'object',
              properties: {
                propertyName: { type: 'string' },
                direction: { type: 'string', enum: ['ASCENDING', 'DESCENDING'] },
              },
            },
            description: 'Sort criteria',
          },
          properties: {
            type: 'array',
            items: { type: 'string' },
            description: 'Properties to retrieve',
          },
          limit: {
            type: 'number',
            description: 'Maximum results (max 100)',
            default: 10,
          },
          after: {
            type: 'string',
            description: 'Pagination cursor',
          },
        },
      },
      handler: async (args: any) => {
        const searchRequest: any = {
          filterGroups: args.filters
            ? [{ filters: args.filters }]
            : undefined,
          query: args.query,
          sorts: args.sorts,
          properties: args.properties,
          limit: Math.min(args.limit || 10, 100),
          after: args.after,
        };

        const response = await client.searchObjects<TicketProperties>('tickets', searchRequest);

        return {
          content: [
            {
              type: 'text',
              text: JSON.stringify(
                {
                  total: response.total,
                  results: response.results,
                  nextCursor: response.paging?.next?.after,
                },
                null,
                2
              ),
            },
          ],
        };
      },
    },
  ];
}
