/**
 * Schedule Delete by Key Tool
 *
 * Hard delete a schedule by its idempotency key.
 * Removes the schedule from the database entirely so the key can be reused.
 */

import { getToolServices } from '../../registry'
import type { Tool } from '../../types'
import { serviceUnavailable } from '../../types'
import { DeleteScheduleByKeyInputSchema, DeleteScheduleByKeyOutputSchema } from './types'
import type { DeleteScheduleByKeyInput } from './types'

export function createScheduleDeleteByKeyTool(): Tool {
  return {
    name: 'schedule_delete_by_key',
    description: 'Hard delete a schedule by its idempotency key. Removes it from the database entirely so the key can be reused for a new schedule.',
    inputSchema: DeleteScheduleByKeyInputSchema,
    outputSchema: DeleteScheduleByKeyOutputSchema,
    async execute({ input, executionContext }) {
      if (!executionContext?.organizationId) {
        throw serviceUnavailable('ExecutionContext', { tool: 'schedule_delete_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_delete_by_key'
        })
      }

      const { idempotencyKey } = input as DeleteScheduleByKeyInput

      await taskSchedulerService.deleteScheduleByIdempotencyKey(
        idempotencyKey,
        executionContext.organizationId
      )

      return { deleted: true }
    }
  }
}
