/**
 * Update Ticket Step — update an existing Autotask ticket.
 * Config: { ticket_id: "{{context.ticket_id}}", fields: { priority: 4, queueID: 123 } }
 */

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

let _client: AutotaskClient | null = null;
function getClient(): AutotaskClient {
  if (!_client) {
    _client = new AutotaskClient({
      apiUrl: process.env.AUTOTASK_API_URL || '',
      username: process.env.AUTOTASK_USERNAME || '',
      password: process.env.AUTOTASK_SECRET || '',
      apiIntegrationCode: process.env.AUTOTASK_API_INTEGRATION_CODE || '',
    });
  }
  return _client;
}

async function executeUpdateTicket(
  step: PipelineStep,
  _context: PipelineContext,
  _executionId: number
): Promise<StepExecutorResult> {
  const ticketId = Number(step.config.ticket_id);
  const fields = step.config.fields || {};

  if (!ticketId || isNaN(ticketId)) {
    return { success: false, error: 'Missing or invalid ticket_id' };
  }

  if (Object.keys(fields).length === 0) {
    return { success: true, output: { updated: false, reason: 'No fields to update' } };
  }

  console.log(`[PIPELINE:update_ticket] Updating ticket #${ticketId}: ${Object.keys(fields).join(', ')}`);

  const client = getClient();
  await client.updateTicket(ticketId, fields);

  return { success: true, output: { updated: true, ticket_id: ticketId, fields_updated: Object.keys(fields) } };
}

registerStepExecutor('update_ticket', executeUpdateTicket);
