/**
 * Report management tools
 */

import type { SalesforceClient } from '../clients/salesforce.js';
import type { Report, ReportMetadata } from '../types/index.js';

export function getTools(client: SalesforceClient) {
  return [
    {
      name: 'sf_list_reports',
      description: 'List available reports. Returns up to 200 reports by default.',
      inputSchema: {
        type: 'object',
        properties: {
          limit: {
            type: 'number',
            description: 'Maximum number of reports to return (default: 200)',
            default: 200,
          },
          offset: {
            type: 'number',
            description: 'Number of records to skip (for pagination)',
          },
        },
      },
      handler: async (args: { limit?: number; offset?: number }) => {
        const soql = client.buildSOQL({
          select: ['Id', 'Name', 'DeveloperName', 'FolderName', 'Description', 'Format', 'LastRunDate', 'Owner.Name', 'CreatedDate'],
          from: 'Report',
          orderBy: 'Name ASC',
          limit: args.limit || 200,
          offset: args.offset,
        });

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

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

    {
      name: 'sf_run_report',
      description: 'Run a report and get its results',
      inputSchema: {
        type: 'object',
        properties: {
          reportId: {
            type: 'string',
            description: 'The Salesforce ID of the report to run',
          },
          includeDetails: {
            type: 'boolean',
            description: 'Include detailed row data (default: true)',
            default: true,
          },
        },
        required: ['reportId'],
      },
      handler: async (args: { reportId: string; includeDetails?: boolean }) => {
        // Use the Analytics API to run the report
        const response = await client['client'].post(
          `/analytics/reports/${args.reportId}`,
          {
            reportMetadata: {
              reportFormat: 'TABULAR',
              detailColumns: args.includeDetails !== false,
            },
          }
        );

        return response.data;
      },
    },

    {
      name: 'sf_describe_report',
      description: 'Get metadata about a report including available fields and filters',
      inputSchema: {
        type: 'object',
        properties: {
          reportId: {
            type: 'string',
            description: 'The Salesforce ID of the report',
          },
        },
        required: ['reportId'],
      },
      handler: async (args: { reportId: string }) => {
        // Use the Analytics API to describe the report
        const response = await client['client'].get(`/analytics/reports/${args.reportId}/describe`);
        return response.data;
      },
    },

    {
      name: 'sf_search_reports',
      description: 'Search for reports by name or developer name',
      inputSchema: {
        type: 'object',
        properties: {
          searchText: {
            type: 'string',
            description: 'Text to search in report name or developer name',
          },
          folderName: {
            type: 'string',
            description: 'Filter by folder name',
          },
          limit: {
            type: 'number',
            description: 'Maximum number of results',
            default: 50,
          },
        },
      },
      handler: async (args: { searchText?: string; folderName?: string; limit?: number }) => {
        const conditions: string[] = [];
        
        if (args.searchText) {
          conditions.push(`(Name LIKE '%${args.searchText}%' OR DeveloperName LIKE '%${args.searchText}%')`);
        }
        
        if (args.folderName) {
          conditions.push(`FolderName = '${args.folderName}'`);
        }

        const soql = client.buildSOQL({
          select: ['Id', 'Name', 'DeveloperName', 'FolderName', 'Description', 'Format', 'LastRunDate'],
          from: 'Report',
          where: conditions.length > 0 ? conditions.join(' AND ') : undefined,
          orderBy: 'Name ASC',
          limit: args.limit || 50,
        });

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