/**
 * RMM Quick Job Step — run a Datto RMM quick job on a device.
 * Config: { device_uid: "{{context.device_uid}}", component_uid: "comp-xxx", variables: [...] }
 */

import { registerStepExecutor } from '../pipeline-engine';
import { DattoRMMClient } from '../datto-rmm-client';
import { PipelineStep, PipelineContext, StepExecutorResult } from '../../types/pipeline';

let _client: DattoRMMClient | null = null;
function getClient(): DattoRMMClient {
  if (!_client) {
    _client = new DattoRMMClient({
      apiUrl: process.env.DATTO_RMM_API_URL || 'https://concord-api.centrastage.net/api/v2',
      apiKey: process.env.DATTO_RMM_API_KEY || '',
      apiSecret: process.env.DATTO_RMM_API_SECRET || '',
    });
  }
  return _client;
}

async function executeRmmQuickJob(
  step: PipelineStep,
  _context: PipelineContext,
  _executionId: number
): Promise<StepExecutorResult> {
  const deviceUid = step.config.device_uid;
  const componentUid = step.config.component_uid;
  const jobName = step.config.job_name || 'Pipeline Quick Job';
  const variables = step.config.variables || [];

  if (!deviceUid) {
    return { success: false, error: 'Missing device_uid for quick job' };
  }
  if (!componentUid) {
    return { success: false, error: 'Missing component_uid for quick job' };
  }

  console.log(`[PIPELINE:rmm_quick_job] Running "${jobName}" on device ${deviceUid}`);

  const client = getClient();
  const result = await client.runQuickJob(deviceUid, {
    jobName,
    jobComponent: {
      componentUid,
      variables,
    },
  });

  return {
    success: true,
    output: {
      quick_job_result: result,
      job_uid: result?.uid || null,
    },
  };
}

registerStepExecutor('rmm_quick_job', executeRmmQuickJob);

/**
 * RMM Get Job Results Step — poll for quick job results.
 * Config: { job_uid: "{{context.job_uid}}", device_uid: "{{context.device_uid}}" }
 */
async function executeRmmGetJobResults(
  step: PipelineStep,
  _context: PipelineContext,
  _executionId: number
): Promise<StepExecutorResult> {
  const jobUid = step.config.job_uid;
  const deviceUid = step.config.device_uid;

  if (!jobUid || !deviceUid) {
    return { success: false, error: 'Missing job_uid or device_uid' };
  }

  const client = getClient();
  const result = await client.getJobResults(jobUid, deviceUid);

  return {
    success: true,
    output: {
      job_results: result,
      job_status: result?.jobDeploymentStatus || 'unknown',
    },
  };
}

registerStepExecutor('rmm_get_job_results', executeRmmGetJobResults);
