/**
 * Enrich Company Step — lookup Autotask company from site name or site_uid.
 * Config: { lookup_by: "site_name", source_field: "{{context.site_name}}" }
 */

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

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

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

  let query: string;
  let params: any[];

  if (lookupBy === 'site_uid') {
    query = `SELECT s.autotask_company_id as company_id, s.autotask_company_name as company_name, s.name as site_name
             FROM datto_rmm_sites s WHERE s.uid = $1 LIMIT 1`;
    params = [sourceValue];
  } else {
    // site_name — fuzzy match
    query = `SELECT s.autotask_company_id as company_id, s.autotask_company_name as company_name, s.name as site_name
             FROM datto_rmm_sites s WHERE LOWER(s.name) = LOWER($1) LIMIT 1`;
    params = [sourceValue];
  }

  const result = await postgresClient.query(query, params);

  if (result.rows.length === 0) {
    // Try companies table directly
    const compResult = await postgresClient.query(
      `SELECT id as company_id, company_name FROM companies
       WHERE LOWER(company_name) LIKE LOWER($1) AND is_deleted = false LIMIT 1`,
      [`%${sourceValue}%`]
    );

    if (compResult.rows.length > 0) {
      return {
        success: true,
        output: {
          company_id: compResult.rows[0].company_id,
          company_name: compResult.rows[0].company_name,
          company_found: true,
        },
      };
    }

    return { success: true, output: { company_id: null, company_name: null, company_found: false } };
  }

  const row = result.rows[0];
  return {
    success: true,
    output: {
      company_id: row.company_id,
      company_name: row.company_name,
      company_found: true,
    },
  };
}

registerStepExecutor('enrich_company', executeEnrichCompany);
