/**
 * HubSpot Companies Tools
 * Tools for managing companies in HubSpot CRM
 */

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

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

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

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

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

    {
      name: 'hubspot_create_company',
      description: 'Create a new company in HubSpot CRM',
      inputSchema: {
        type: 'object',
        properties: {
          name: {
            type: 'string',
            description: 'Company name (required)',
          },
          domain: {
            type: 'string',
            description: 'Company domain/website',
          },
          industry: {
            type: 'string',
            description: 'Industry',
          },
          phone: {
            type: 'string',
            description: 'Company phone number',
          },
          city: {
            type: 'string',
            description: 'City',
          },
          state: {
            type: 'string',
            description: 'State/region',
          },
          country: {
            type: 'string',
            description: 'Country',
          },
          numberofemployees: {
            type: 'string',
            description: 'Number of employees',
          },
          annualrevenue: {
            type: 'string',
            description: 'Annual revenue',
          },
          additionalProperties: {
            type: 'object',
            description: 'Additional custom properties as key-value pairs',
          },
        },
        required: ['name'],
      },
      handler: async (args: any) => {
        const properties: CompanyProperties = {
          name: args.name,
          domain: args.domain,
          industry: args.industry,
          phone: args.phone,
          city: args.city,
          state: args.state,
          country: args.country,
          numberofemployees: args.numberofemployees,
          annualrevenue: args.annualrevenue,
          ...(args.additionalProperties || {}),
        };

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

        const company = await client.createObject<CompanyProperties>('companies', properties);

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

    {
      name: 'hubspot_update_company',
      description: 'Update an existing company',
      inputSchema: {
        type: 'object',
        properties: {
          companyId: {
            type: 'string',
            description: 'HubSpot company ID',
          },
          name: {
            type: 'string',
            description: 'Updated company name',
          },
          domain: {
            type: 'string',
            description: 'Updated domain',
          },
          industry: {
            type: 'string',
            description: 'Updated industry',
          },
          additionalProperties: {
            type: 'object',
            description: 'Additional properties to update as key-value pairs',
          },
        },
        required: ['companyId'],
      },
      handler: async (args: any) => {
        const properties: Partial<CompanyProperties> = {
          name: args.name,
          domain: args.domain,
          industry: args.industry,
          ...(args.additionalProperties || {}),
        };

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

        const company = await client.updateObject<CompanyProperties>(
          'companies',
          args.companyId,
          properties
        );

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

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

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

    {
      name: 'hubspot_search_companies',
      description: 'Search companies 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<CompanyProperties>('companies', 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_companies',
      description: 'Create multiple companies in a single batch request (up to 100)',
      inputSchema: {
        type: 'object',
        properties: {
          companies: {
            type: 'array',
            items: {
              type: 'object',
              properties: {
                name: { type: 'string' },
                domain: { type: 'string' },
                industry: { type: 'string' },
                city: { type: 'string' },
              },
            },
            description: 'Array of company objects to create',
          },
        },
        required: ['companies'],
      },
      handler: async (args: any) => {
        const inputs = args.companies.map((c: any) => ({ properties: c }));
        const response = await client.batchCreateObjects<CompanyProperties>('companies', { inputs });

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

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

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