/**
 * AI Title Step — uses AI to clean up messy ticket titles.
 * Config: {
 *   template_purpose: 'title_cleanup'
 * }
 * Condition: typically checks if title needs cleanup (from classification.ai_reasons)
 */

import { registerWorkflowStepExecutor } from '../ticket-workflow-engine';
import { aiTriageService } from '../ai-triage-service';
import { TicketWorkflowStep, WorkflowStepContext, WorkflowStepResult } from '../../types/ticket-workflow';

async function executeAiTitle(
  step: TicketWorkflowStep,
  context: WorkflowStepContext,
  _executionId: number
): Promise<WorkflowStepResult> {
  const ticket = context.ticket;

  // Call AI title cleanup
  const cleanedTitle = await aiTriageService.cleanupTitle(ticket, context._settings);

  if (!cleanedTitle || cleanedTitle === ticket.title) {
    return {
      success: true,
      output: {
        skipped: true,
        reason: 'No title cleanup needed or AI returned same title'
      }
    };
  }

  // Update field changes
  if (!context.field_changes) {
    context.field_changes = {};
  }

  context.field_changes['title'] = {
    before: ticket.title,
    after: cleanedTitle
  };

  return {
    success: true,
    output: {
      method: 'ai',
      original_title: ticket.title,
      cleaned_title: cleanedTitle
    }
  };
}

registerWorkflowStepExecutor('ai_title', executeAiTitle);
