/**
 * Schedule Cancel by Metadata Tool
 *
 * Batch cancel (soft delete) task schedules matching metadata filters.
 * Sets status to 'cancelled' and clears next_run_at.
 */

import { getToolServices } from '../../registry'
import type { Tool } from '../../types'
import { serviceUnavailable } from '../../types'
import { CancelSchedulesByMetadataInputSchema, CancelSchedulesByMetadataOutputSchema } from './types'
import type { CancelSchedulesByMetadataInput } from './types'

export function createScheduleCancelByMetadataTool(): Tool {
  return {
    name: 'schedule_cancel_by_metadata',
    description: 'Cancel all active schedules matching metadata filters. Performs a soft delete (sets status to cancelled). Use for batch cleanup when a contact unsubscribes or a deal is closed.',
    inputSchema: CancelSchedulesByMetadataInputSchema,
    outputSchema: CancelSchedulesByMetadataOutputSchema,
    async execute({ input, executionContext }) {
      if (!executionContext?.organizationId) {
        throw serviceUnavailable('ExecutionContext', { tool: 'schedule_cancel_by_metadata', reason: 'organizationId required for multi-tenant isolation' })
      }

      const { taskSchedulerService } = getToolServices()
      if (!taskSchedulerService) {
        throw serviceUnavailable('TaskSchedulerService', {
          message: 'Ensure toolServicesRegistry.initialize() was called in apps/api/src/main.ts',
          tool: 'schedule_cancel_by_metadata'
        })
      }

      const { metadata, status } = input as CancelSchedulesByMetadataInput

      return taskSchedulerService.cancelSchedulesByMetadata(
        executionContext.organizationId,
        metadata,
        status
      )
    }
  }
}
