/**
 * HubSpot Deals Tools
 * Tools for managing deals in HubSpot CRM
 */

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

export function getTools(client: HubSpotClient) {
  return [
    {
      name: 'hubspot_list_deals',
      description: 'List deals with pagination. Returns up to 100 deals per request.',
      inputSchema: {
        type: 'object',
        properties: {
          limit: {
            type: 'number',
            description: 'Maximum number of deals 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., ["dealname", "amount", "dealstage"])',
          },
        },
      },
      handler: async (args: any) => {
        const response = await client.listObjects<DealProperties>('deals', {
          limit: Math.min(args.limit || 10, 100),
          after: args.after,
          properties: args.properties,
        });

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

    {
      name: 'hubspot_get_deal',
      description: 'Get a single deal by ID with all details',
      inputSchema: {
        type: 'object',
        properties: {
          dealId: {
            type: 'string',
            description: 'HubSpot deal 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: ['dealId'],
      },
      handler: async (args: any) => {
        const deal = await client.getObject<DealProperties>(
          'deals',
          args.dealId,
          args.properties,
          args.associations
        );

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

    {
      name: 'hubspot_create_deal',
      description: 'Create a new deal in HubSpot CRM',
      inputSchema: {
        type: 'object',
        properties: {
          dealname: {
            type: 'string',
            description: 'Deal name (required)',
          },
          amount: {
            type: 'string',
            description: 'Deal amount',
          },
          dealstage: {
            type: 'string',
            description: 'Deal stage ID',
          },
          pipeline: {
            type: 'string',
            description: 'Pipeline ID',
          },
          closedate: {
            type: 'string',
            description: 'Expected close date (ISO format)',
          },
          hubspot_owner_id: {
            type: 'string',
            description: 'Owner/user ID',
          },
          description: {
            type: 'string',
            description: 'Deal description',
          },
          additionalProperties: {
            type: 'object',
            description: 'Additional custom properties as key-value pairs',
          },
        },
        required: ['dealname'],
      },
      handler: async (args: any) => {
        const properties: DealProperties = {
          dealname: args.dealname,
          amount: args.amount,
          dealstage: args.dealstage,
          pipeline: args.pipeline,
          closedate: args.closedate,
          hubspot_owner_id: args.hubspot_owner_id,
          description: args.description,
          ...(args.additionalProperties || {}),
        };

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

        const deal = await client.createObject<DealProperties>('deals', properties);

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

    {
      name: 'hubspot_update_deal',
      description: 'Update an existing deal',
      inputSchema: {
        type: 'object',
        properties: {
          dealId: {
            type: 'string',
            description: 'HubSpot deal ID',
          },
          dealname: {
            type: 'string',
            description: 'Updated deal name',
          },
          amount: {
            type: 'string',
            description: 'Updated amount',
          },
          dealstage: {
            type: 'string',
            description: 'Updated deal stage ID',
          },
          closedate: {
            type: 'string',
            description: 'Updated close date',
          },
          additionalProperties: {
            type: 'object',
            description: 'Additional properties to update as key-value pairs',
          },
        },
        required: ['dealId'],
      },
      handler: async (args: any) => {
        const properties: Partial<DealProperties> = {
          dealname: args.dealname,
          amount: args.amount,
          dealstage: args.dealstage,
          closedate: args.closedate,
          ...(args.additionalProperties || {}),
        };

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

        const deal = await client.updateObject<DealProperties>(
          'deals',
          args.dealId,
          properties
        );

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

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

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

    {
      name: 'hubspot_move_deal_stage',
      description: 'Move a deal to a different stage in the pipeline',
      inputSchema: {
        type: 'object',
        properties: {
          dealId: {
            type: 'string',
            description: 'HubSpot deal ID',
          },
          dealstage: {
            type: 'string',
            description: 'New deal stage ID to move to',
          },
        },
        required: ['dealId', 'dealstage'],
      },
      handler: async (args: any) => {
        const deal = await client.updateObject<DealProperties>('deals', args.dealId, {
          dealstage: args.dealstage,
        });

        return {
          content: [
            {
              type: 'text',
              text: JSON.stringify(
                {
                  success: true,
                  message: `Deal ${args.dealId} moved to stage ${args.dealstage}`,
                  deal,
                },
                null,
                2
              ),
            },
          ],
        };
      },
    },

    {
      name: 'hubspot_search_deals',
      description: 'Search deals 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<DealProperties>('deals', searchRequest);

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

    {
      name: 'hubspot_batch_create_deals',
      description: 'Create multiple deals in a single batch request (up to 100)',
      inputSchema: {
        type: 'object',
        properties: {
          deals: {
            type: 'array',
            items: {
              type: 'object',
              properties: {
                dealname: { type: 'string' },
                amount: { type: 'string' },
                dealstage: { type: 'string' },
                pipeline: { type: 'string' },
              },
            },
            description: 'Array of deal objects to create',
          },
        },
        required: ['deals'],
      },
      handler: async (args: any) => {
        const inputs = args.deals.map((d: any) => ({ properties: d }));
        const response = await client.batchCreateObjects<DealProperties>('deals', { inputs });

        return {
          content: [
            {
              type: 'text',
              text: JSON.stringify(
                {
                  success: true,
                  created: response.results.length,
                  deals: response.results,
                  errors: response.errors,
                },
                null,
                2
              ),
            },
          ],
        };
      },
    },

    {
      name: 'hubspot_batch_update_deals',
      description: 'Update multiple deals in a single batch request (up to 100)',
      inputSchema: {
        type: 'object',
        properties: {
          updates: {
            type: 'array',
            items: {
              type: 'object',
              properties: {
                id: { type: 'string', description: 'Deal ID' },
                properties: { type: 'object', description: 'Properties to update' },
              },
              required: ['id', 'properties'],
            },
            description: 'Array of deal updates',
          },
        },
        required: ['updates'],
      },
      handler: async (args: any) => {
        const response = await client.batchUpdateObjects<DealProperties>('deals', {
          inputs: args.updates,
        });

        return {
          content: [
            {
              type: 'text',
              text: JSON.stringify(
                {
                  success: true,
                  updated: response.results.length,
                  deals: response.results,
                  errors: response.errors,
                },
                null,
                2
              ),
            },
          ],
        };
      },
    },
  ];
}
