/**
 * Validate Step — validates classification results against DB picklists.
 * Config: {
 *   required_fields?: string[]  // optional list of fields that must be present
 * }
 */

import { registerWorkflowStepExecutor } from '../ticket-workflow-engine';
import { triageValidator } from '../triage-validator';
import { TicketWorkflowStep, WorkflowStepContext, WorkflowStepResult } from '../../types/ticket-workflow';
import { ClassificationResult } from '../../types/workflow';

async function executeValidate(
  step: TicketWorkflowStep,
  context: WorkflowStepContext,
  _executionId: number
): Promise<WorkflowStepResult> {
  // Build ClassificationResult from context.classification
  const classification: ClassificationResult = {
    branch: context.classification?.branch_routing || null,
    ticket_type: context.classification?.ticket_type || null,
    issue_classification: context.classification?.issue_classification || null,
    priority: context.classification?.priority || null,
    queue: context.classification?.queue_routing || null,
    overall_confidence: 'medium',
    needs_ai: false,
    ai_reasons: []
  };

  // Run validation
  const validationResult = await triageValidator.validate(classification);

  // Store validation result in context for later steps
  context.validation = validationResult;

  // Check for failed fields
  const validationFailedFields = validationResult.errors.map(e => e.field);

  return {
    success: true,
    output: {
      is_valid: validationResult.is_valid,
      validation_errors: validationResult.errors,
      validation_failed_fields: validationFailedFields,
      total_errors: validationResult.errors.length
    }
  };
}

registerWorkflowStepExecutor('validate', executeValidate);
