<?php

namespace PloverCRM\Modules\Automations\Services;

use PloverCRM\Core\Container;
use PloverCRM\Modules\Automations\Actions\SendInternalEmailAction;
use PloverCRM\Modules\Automations\Actions\SendGoogleAdsConversionAction;
use PloverCRM\Modules\Automations\Actions\SendMetaCapiEventAction;

/**
 * Executes automations against a normalized event payload.
 */
class AutomationRunner
{
    private Container $container;

    public function __construct(Container $container)
    {
        $this->container = $container;
    }

    public function run(array $automation, array $payload): void
    {
        $definition = $automation['definition_json'] ?? [];
        $conditions = $definition['conditions'] ?? [];

        if (!AutomationConditionEvaluator::passes($conditions, $payload)) {
            return;
        }

        $runId = AutomationRunRepository::startRun(
            (int) $automation['id'],
            (string) ($payload['event_name'] ?? ''),
            isset($payload['contact']['id']) ? (int) $payload['contact']['id'] : null,
            $payload
        );

        try {
            $results = [];

            foreach (($definition['actions'] ?? []) as $action) {
                $results[] = $this->executeAction($action, $payload);
            }

            AutomationRunRepository::completeRun($runId, 'success', [
                'actions' => $results,
            ]);
            AutomationRepository::touchLastRun((int) $automation['id']);
        } catch (\Throwable $e) {
            AutomationRunRepository::completeRun($runId, 'failed', [], $e->getMessage());
        }
    }

    private function executeAction(array $action, array $payload): array
    {
        $type = $action['type'] ?? '';
        $config = $action['config'] ?? [];

        switch ($type) {
            case 'send_internal_email':
                $handler = new SendInternalEmailAction();
                return $handler->execute($config, $payload);
            case 'send_google_ads_conversion':
                $handler = new SendGoogleAdsConversionAction();
                return $handler->execute($config, $payload);
            case 'send_meta_capi_event':
                $handler = new SendMetaCapiEventAction();
                return $handler->execute($config, $payload);
        }

        throw new \RuntimeException('Unsupported automation action: ' . $type);
    }
}
