/**
 * Enrich Ticket Step — fetch ticket from local DB or Autotask.
 * Config: { lookup_by: "ticket_number"|"ticket_id", source_field: "{{context.ticket_number}}" }
 */

import { registerStepExecutor } from '../pipeline-engine';
import { postgresClient } from '../postgres-client';
import { PipelineStep, PipelineContext, StepExecutorResult } from '../../types/pipeline';

async function executeEnrichTicket(
  step: PipelineStep,
  _context: PipelineContext,
  _executionId: number
): Promise<StepExecutorResult> {
  const lookupBy = step.config.lookup_by || 'ticket_number';
  const sourceValue = step.config.source_field;

  if (!sourceValue) {
    return { success: false, error: `No source value for ticket lookup by ${lookupBy}` };
  }

  const field = lookupBy === 'ticket_id' ? 'id' : 'ticket_number';
  const result = await postgresClient.query(
    `SELECT id, ticket_number, title, description, status, priority, queue_id,
            company_id, contact_id, assigned_resource_id, ticket_type,
            issue_type, sub_issue_type, ticket_category
     FROM tickets WHERE ${field} = $1 AND is_deleted = false LIMIT 1`,
    [sourceValue]
  );

  if (result.rows.length === 0) {
    return { success: true, output: { ticket: null, ticket_found: false } };
  }

  const ticket = result.rows[0];
  return {
    success: true,
    output: {
      ticket,
      ticket_found: true,
      ticket_id: ticket.id,
      ticket_number: ticket.ticket_number,
      ticket_title: ticket.title,
    },
  };
}

registerStepExecutor('enrich_ticket', executeEnrichTicket);
