/**
 * Task management tools
 */

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

export function getTools(client: SalesforceClient) {
  return [
    {
      name: 'sf_list_tasks',
      description: 'List tasks with optional filters. Returns up to 200 tasks by default.',
      inputSchema: {
        type: 'object',
        properties: {
          limit: {
            type: 'number',
            description: 'Maximum number of tasks 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., "ActivityDate ASC", "CreatedDate DESC")',
            default: 'ActivityDate ASC',
          },
          status: {
            type: 'string',
            description: 'Filter by status (e.g., "Not Started", "In Progress", "Completed")',
          },
          priority: {
            type: 'string',
            description: 'Filter by priority (e.g., "High", "Normal", "Low")',
          },
          isClosed: {
            type: 'boolean',
            description: 'Filter by closed status',
          },
        },
      },
      handler: async (args: {
        limit?: number;
        offset?: number;
        orderBy?: string;
        status?: string;
        priority?: string;
        isClosed?: boolean;
      }) => {
        const conditions: string[] = [];
        if (args.status) conditions.push(`Status = '${args.status}'`);
        if (args.priority) conditions.push(`Priority = '${args.priority}'`);
        if (args.isClosed !== undefined) conditions.push(`IsClosed = ${args.isClosed}`);

        const soql = client.buildSOQL({
          select: ['Id', 'Subject', 'Status', 'Priority', 'ActivityDate', 'Description', 'IsClosed', 'IsHighPriority', 'Who.Name', 'What.Name', 'Owner.Name', 'CreatedDate'],
          from: 'Task',
          where: conditions.length > 0 ? conditions.join(' AND ') : undefined,
          orderBy: args.orderBy || 'ActivityDate ASC',
          limit: args.limit || 200,
          offset: args.offset,
        });

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

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

    {
      name: 'sf_create_task',
      description: 'Create a new task',
      inputSchema: {
        type: 'object',
        properties: {
          subject: {
            type: 'string',
            description: 'Task subject/title (required)',
          },
          status: {
            type: 'string',
            description: 'Task status (required, e.g., "Not Started", "In Progress")',
          },
          priority: {
            type: 'string',
            description: 'Priority (e.g., "High", "Normal", "Low")',
          },
          activityDate: {
            type: 'string',
            description: 'Due date in YYYY-MM-DD format',
          },
          description: {
            type: 'string',
            description: 'Task description',
          },
          whoId: {
            type: 'string',
            description: 'Related Lead or Contact ID',
          },
          whatId: {
            type: 'string',
            description: 'Related Account, Opportunity, or other object ID',
          },
        },
        required: ['subject', 'status'],
      },
      handler: async (args: {
        subject: string;
        status: string;
        priority?: string;
        activityDate?: string;
        description?: string;
        whoId?: string;
        whatId?: string;
      }) => {
        const taskData: Partial<Task> = {
          Subject: args.subject,
          Status: args.status,
          Priority: args.priority,
          ActivityDate: args.activityDate,
          Description: args.description,
          WhoId: args.whoId as any,
          WhatId: args.whatId as any,
        };

        const result = await client.createRecord('Task', taskData);
        return result;
      },
    },

    {
      name: 'sf_update_task',
      description: 'Update an existing task',
      inputSchema: {
        type: 'object',
        properties: {
          taskId: {
            type: 'string',
            description: 'The Salesforce ID of the task to update',
          },
          subject: { type: 'string' },
          status: { type: 'string' },
          priority: { type: 'string' },
          activityDate: { type: 'string', description: 'Due date in YYYY-MM-DD format' },
          description: { type: 'string' },
          whoId: { type: 'string' },
          whatId: { type: 'string' },
        },
        required: ['taskId'],
      },
      handler: async (args: {
        taskId: string;
        subject?: string;
        status?: string;
        priority?: string;
        activityDate?: string;
        description?: string;
        whoId?: string;
        whatId?: string;
      }) => {
        const { taskId, ...updates } = args;
        const taskData: Partial<Task> = {
          Subject: updates.subject,
          Status: updates.status,
          Priority: updates.priority,
          ActivityDate: updates.activityDate,
          Description: updates.description,
          WhoId: updates.whoId as any,
          WhatId: updates.whatId as any,
        };

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

        await client.updateRecord('Task', taskId, taskData);
        return { success: true, id: taskId };
      },
    },

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

    {
      name: 'sf_search_tasks',
      description: 'Search tasks using SOQL with flexible criteria',
      inputSchema: {
        type: 'object',
        properties: {
          searchText: {
            type: 'string',
            description: 'Text to search in Subject and Description fields',
          },
          whereClause: {
            type: 'string',
            description: 'Custom WHERE clause (e.g., "Priority = \'High\' AND IsClosed = false")',
          },
          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 = `(Subject LIKE '%${args.searchText}%' OR Description LIKE '%${args.searchText}%')`;
          where = where ? `${searchCondition} AND (${where})` : searchCondition;
        }

        const soql = client.buildSOQL({
          select: ['Id', 'Subject', 'Status', 'Priority', 'ActivityDate', 'IsClosed', 'IsHighPriority', 'Who.Name', 'What.Name', 'Owner.Name'],
          from: 'Task',
          where,
          orderBy: 'ActivityDate ASC',
          limit: args.limit || 100,
        });

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

    {
      name: 'sf_get_overdue_tasks',
      description: 'Get all overdue tasks (tasks with ActivityDate in the past and not closed)',
      inputSchema: {
        type: 'object',
        properties: {
          limit: {
            type: 'number',
            description: 'Maximum number of results',
            default: 100,
          },
        },
      },
      handler: async (args: { limit?: number }) => {
        const today = new Date().toISOString().split('T')[0];
        const soql = client.buildSOQL({
          select: ['Id', 'Subject', 'Status', 'Priority', 'ActivityDate', 'Who.Name', 'What.Name', 'Owner.Name', 'CreatedDate'],
          from: 'Task',
          where: `ActivityDate < ${today} AND IsClosed = false`,
          orderBy: 'ActivityDate ASC',
          limit: args.limit || 100,
        });

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