/**
 * Account management tools
 */

import type { SalesforceClient } from '../clients/salesforce.js';
import type { Account } from '../types/index.js';

export function getTools(client: SalesforceClient) {
  return [
    {
      name: 'sf_list_accounts',
      description: 'List accounts with optional filters. Returns up to 200 accounts by default.',
      inputSchema: {
        type: 'object',
        properties: {
          limit: {
            type: 'number',
            description: 'Maximum number of accounts to return (default: 200)',
            default: 200,
          },
          offset: {
            type: 'number',
            description: 'Number of records to skip (for pagination)',
          },
          orderBy: {
            type: 'string',
            description: 'Field to sort by (e.g., "Name ASC", "CreatedDate DESC")',
            default: 'Name ASC',
          },
          type: {
            type: 'string',
            description: 'Filter by account type (e.g., "Customer", "Prospect")',
          },
          industry: {
            type: 'string',
            description: 'Filter by industry',
          },
        },
      },
      handler: async (args: {
        limit?: number;
        offset?: number;
        orderBy?: string;
        type?: string;
        industry?: string;
      }) => {
        const conditions: string[] = [];
        if (args.type) conditions.push(`Type = '${args.type}'`);
        if (args.industry) conditions.push(`Industry = '${args.industry}'`);

        const soql = client.buildSOQL({
          select: ['Id', 'Name', 'Type', 'Industry', 'Phone', 'Website', 'BillingCity', 'BillingState', 'Owner.Name', 'CreatedDate'],
          from: 'Account',
          where: conditions.length > 0 ? conditions.join(' AND ') : undefined,
          orderBy: args.orderBy || 'Name ASC',
          limit: args.limit || 200,
          offset: args.offset,
        });

        const result = await client.query<Account>(soql);
        return {
          totalSize: result.totalSize,
          records: result.records,
          hasMore: !result.done,
        };
      },
    },

    {
      name: 'sf_get_account',
      description: 'Get detailed information about a specific account by ID',
      inputSchema: {
        type: 'object',
        properties: {
          accountId: {
            type: 'string',
            description: 'The Salesforce ID of the account (15 or 18 characters)',
          },
        },
        required: ['accountId'],
      },
      handler: async (args: { accountId: string }) => {
        const account = await client.getRecord<Account>('Account', args.accountId);
        return account;
      },
    },

    {
      name: 'sf_create_account',
      description: 'Create a new account',
      inputSchema: {
        type: 'object',
        properties: {
          name: {
            type: 'string',
            description: 'Account name (required)',
          },
          type: {
            type: 'string',
            description: 'Account type (e.g., "Customer", "Prospect", "Partner")',
          },
          industry: {
            type: 'string',
            description: 'Industry (e.g., "Technology", "Healthcare", "Finance")',
          },
          phone: {
            type: 'string',
            description: 'Phone number',
          },
          website: {
            type: 'string',
            description: 'Website URL',
          },
          billingStreet: {
            type: 'string',
            description: 'Billing street address',
          },
          billingCity: {
            type: 'string',
            description: 'Billing city',
          },
          billingState: {
            type: 'string',
            description: 'Billing state/province',
          },
          billingPostalCode: {
            type: 'string',
            description: 'Billing postal code',
          },
          billingCountry: {
            type: 'string',
            description: 'Billing country',
          },
          description: {
            type: 'string',
            description: 'Account description',
          },
          numberOfEmployees: {
            type: 'number',
            description: 'Number of employees',
          },
          annualRevenue: {
            type: 'number',
            description: 'Annual revenue',
          },
        },
        required: ['name'],
      },
      handler: async (args: {
        name: string;
        type?: string;
        industry?: string;
        phone?: string;
        website?: string;
        billingStreet?: string;
        billingCity?: string;
        billingState?: string;
        billingPostalCode?: string;
        billingCountry?: string;
        description?: string;
        numberOfEmployees?: number;
        annualRevenue?: number;
      }) => {
        const accountData: Partial<Account> = {
          Name: args.name,
          Type: args.type,
          Industry: args.industry,
          Phone: args.phone,
          Website: args.website,
          BillingStreet: args.billingStreet,
          BillingCity: args.billingCity,
          BillingState: args.billingState,
          BillingPostalCode: args.billingPostalCode,
          BillingCountry: args.billingCountry,
          Description: args.description,
          NumberOfEmployees: args.numberOfEmployees,
          AnnualRevenue: args.annualRevenue,
        };

        const result = await client.createRecord('Account', accountData);
        return result;
      },
    },

    {
      name: 'sf_update_account',
      description: 'Update an existing account',
      inputSchema: {
        type: 'object',
        properties: {
          accountId: {
            type: 'string',
            description: 'The Salesforce ID of the account to update',
          },
          name: {
            type: 'string',
            description: 'Account name',
          },
          type: {
            type: 'string',
            description: 'Account type',
          },
          industry: {
            type: 'string',
            description: 'Industry',
          },
          phone: {
            type: 'string',
            description: 'Phone number',
          },
          website: {
            type: 'string',
            description: 'Website URL',
          },
          billingStreet: {
            type: 'string',
            description: 'Billing street address',
          },
          billingCity: {
            type: 'string',
            description: 'Billing city',
          },
          billingState: {
            type: 'string',
            description: 'Billing state/province',
          },
          billingPostalCode: {
            type: 'string',
            description: 'Billing postal code',
          },
          billingCountry: {
            type: 'string',
            description: 'Billing country',
          },
          description: {
            type: 'string',
            description: 'Account description',
          },
          numberOfEmployees: {
            type: 'number',
            description: 'Number of employees',
          },
          annualRevenue: {
            type: 'number',
            description: 'Annual revenue',
          },
        },
        required: ['accountId'],
      },
      handler: async (args: {
        accountId: string;
        name?: string;
        type?: string;
        industry?: string;
        phone?: string;
        website?: string;
        billingStreet?: string;
        billingCity?: string;
        billingState?: string;
        billingPostalCode?: string;
        billingCountry?: string;
        description?: string;
        numberOfEmployees?: number;
        annualRevenue?: number;
      }) => {
        const { accountId, ...updates } = args;
        const accountData: Partial<Account> = {
          Name: updates.name,
          Type: updates.type,
          Industry: updates.industry,
          Phone: updates.phone,
          Website: updates.website,
          BillingStreet: updates.billingStreet,
          BillingCity: updates.billingCity,
          BillingState: updates.billingState,
          BillingPostalCode: updates.billingPostalCode,
          BillingCountry: updates.billingCountry,
          Description: updates.description,
          NumberOfEmployees: updates.numberOfEmployees,
          AnnualRevenue: updates.annualRevenue,
        };

        // Remove undefined values
        Object.keys(accountData).forEach((key) => {
          if (accountData[key as keyof Account] === undefined) {
            delete accountData[key as keyof Account];
          }
        });

        await client.updateRecord('Account', accountId, accountData);
        return { success: true, id: accountId };
      },
    },

    {
      name: 'sf_delete_account',
      description: 'Delete an account by ID',
      inputSchema: {
        type: 'object',
        properties: {
          accountId: {
            type: 'string',
            description: 'The Salesforce ID of the account to delete',
          },
        },
        required: ['accountId'],
      },
      handler: async (args: { accountId: string }) => {
        await client.deleteRecord('Account', args.accountId);
        return { success: true, id: args.accountId };
      },
    },

    {
      name: 'sf_search_accounts',
      description: 'Search accounts using SOQL with flexible criteria',
      inputSchema: {
        type: 'object',
        properties: {
          searchText: {
            type: 'string',
            description: 'Text to search in Name, BillingCity, or Website fields',
          },
          whereClause: {
            type: 'string',
            description: 'Custom WHERE clause (e.g., "AnnualRevenue > 1000000")',
          },
          limit: {
            type: 'number',
            description: 'Maximum number of results',
            default: 100,
          },
        },
      },
      handler: async (args: { searchText?: string; whereClause?: string; limit?: number }) => {
        let where = args.whereClause;
        
        if (args.searchText) {
          const searchCondition = `(Name LIKE '%${args.searchText}%' OR BillingCity LIKE '%${args.searchText}%' OR Website LIKE '%${args.searchText}%')`;
          where = where ? `${searchCondition} AND (${where})` : searchCondition;
        }

        const soql = client.buildSOQL({
          select: ['Id', 'Name', 'Type', 'Industry', 'Phone', 'Website', 'BillingCity', 'BillingState', 'AnnualRevenue', 'NumberOfEmployees'],
          from: 'Account',
          where,
          orderBy: 'Name ASC',
          limit: args.limit || 100,
        });

        const result = await client.query<Account>(soql);
        return result.records;
      },
    },
  ];
}
