/**
 * Schedule Cancel by Key Tool
 *
 * Cancel a single schedule by its idempotency key (soft delete).
 * Finds the schedule by key and cancels it. No-op if not found.
 */

import { getToolServices } from '../../registry'
import type { Tool } from '../../types'
import { serviceUnavailable } from '../../types'
import { CancelScheduleByKeyInputSchema, CancelScheduleByKeyOutputSchema } from './types'
import type { CancelScheduleByKeyInput } from './types'

export function createScheduleCancelByKeyTool(): Tool {
  return {
    name: 'schedule_cancel_by_key',
    description: 'Cancel a schedule by its idempotency key (soft delete). Sets status to cancelled. Returns whether a schedule was found and cancelled.',
    inputSchema: CancelScheduleByKeyInputSchema,
    outputSchema: CancelScheduleByKeyOutputSchema,
    async execute({ input, executionContext }) {
      if (!executionContext?.organizationId) {
        throw serviceUnavailable('ExecutionContext', { tool: 'schedule_cancel_by_key', 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_key'
        })
      }

      const { idempotencyKey } = input as CancelScheduleByKeyInput

      const schedule = await taskSchedulerService.findByIdempotencyKey(
        executionContext.organizationId,
        idempotencyKey
      )

      if (!schedule) {
        return { cancelled: false }
      }

      await taskSchedulerService.cancelSchedule(schedule.id, executionContext.organizationId)
      return { cancelled: true }
    }
  }
}
