/**
 * Create Note Step — add a note to an Autotask ticket.
 * Config: { ticket_id: "{{context.ticket_id}}", title: "...", body: "...", note_type: 1, publish: 1 }
 */

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 executeCreateNote(
  step: PipelineStep,
  _context: PipelineContext,
  _executionId: number
): Promise<StepExecutorResult> {
  const ticketId = Number(step.config.ticket_id);
  const title = step.config.title || 'Pipeline Note';
  const body = step.config.body || '';
  const noteType = Number(step.config.note_type) || 1;
  const publish = Number(step.config.publish) || 1;

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

  console.log(`[PIPELINE:create_note] Adding note to ticket #${ticketId}: "${title}"`);

  const client = getClient();
  await client.createEntity('TicketNotes', {
    ticketID: ticketId,
    title,
    description: body,
    noteType,
    publish,
  });

  return { success: true, output: { note_created: true, ticket_id: ticketId } };
}

registerStepExecutor('create_note', executeCreateNote);
