/**
 * HITL Cancel by Metadata Tool
 *
 * Batch delete pending HITL (command queue) tasks matching metadata filters.
 * Used for cleanup when a contact unsubscribes or a deal is closed.
 */

import { z } from 'zod'
import { getToolServices } from '../../registry'
import type { Tool } from '../../types'
import { serviceUnavailable } from '../../types'

// ============================================
// Schemas
// ============================================

export const HitlCancelByMetadataInputSchema = z.object({
  /** JSONB containment filter for metadata (e.g., { contactEmail: 'user@example.com' }) */
  metadata: z.record(z.string(), z.unknown()),
  /** Only delete tasks with this status (default: 'pending') */
  status: z.string().default('pending')
})

export const HitlCancelByMetadataOutputSchema = z.object({
  deleted: z.number()
})

export type HitlCancelByMetadataInput = z.infer<typeof HitlCancelByMetadataInputSchema>
export type HitlCancelByMetadataOutput = z.infer<typeof HitlCancelByMetadataOutputSchema>

// ============================================
// Tool Factory
// ============================================

export function createHitlCancelByMetadataTool(): Tool {
  return {
    name: 'hitl_cancel_by_metadata',
    description:
      'Delete pending HITL (human-in-the-loop) tasks matching metadata filters. Used for batch cleanup of command queue entries when a contact unsubscribes or a deal is closed.',
    inputSchema: HitlCancelByMetadataInputSchema,
    outputSchema: HitlCancelByMetadataOutputSchema,
    async execute({ input, executionContext }) {
      if (!executionContext?.organizationId) {
        throw serviceUnavailable('ExecutionContext', { tool: 'hitl_cancel_by_metadata', reason: 'organizationId required for multi-tenant isolation' })
      }

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

      const { metadata, status } = input as HitlCancelByMetadataInput

      return commandQueueService.deleteByMetadata(
        executionContext.organizationId,
        metadata,
        status
      )
    }
  }
}
