/**
 * Enrich Device Step — fetch device details from Datto RMM or local DB.
 * Config: { lookup_by: "device_uid", source_field: "{{context.device_uid}}" }
 */

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

async function executeEnrichDevice(
  step: PipelineStep,
  _context: PipelineContext,
  _executionId: number
): Promise<StepExecutorResult> {
  const deviceUid = step.config.source_field || step.config.device_uid;

  if (!deviceUid) {
    return { success: false, error: 'No device_uid provided for enrichment' };
  }

  // Try local DB first
  const result = await postgresClient.query(
    `SELECT d.*, s.name as site_name, s.autotask_company_id, s.autotask_company_name
     FROM datto_rmm_devices d
     LEFT JOIN datto_rmm_sites s ON s.id = d.site_id
     WHERE d.uid = $1
     LIMIT 1`,
    [deviceUid]
  );

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

  const device = result.rows[0];
  return {
    success: true,
    output: {
      device,
      device_found: true,
      device_hostname: device.hostname,
      device_os: device.operating_system,
      device_ip: device.int_ip_address || device.ext_ip_address,
      company_id: device.autotask_company_id,
      company_name: device.autotask_company_name,
    },
  };
}

registerStepExecutor('enrich_device', executeEnrichDevice);
