<?php

namespace PloverCRM\Modules\Integrations\Services;

use PloverCRM\Core\Plugin;

/**
 * Resolves the correct Google Ads conversion action for a stage-based automation.
 *
 * If no conversion action is provided, it creates or reuses one using the
 * selected stage name so the UI can stay simple.
 */
class GoogleAdsConversionActionResolver
{
    /**
     * @return array{id:string,name:string}
     */
    public static function ensureForStage(
        int $connectionId,
        string $stageId,
        string $conversionActionId = '',
        string $conversionActionName = ''
    ): array {
        $stageName = self::resolveStageName($stageId);

        if ($conversionActionId !== '') {
            return [
                'id' => sanitize_text_field($conversionActionId),
                'name' => sanitize_text_field($conversionActionName !== '' ? $conversionActionName : $stageName),
            ];
        }

        $connection = GoogleAdsConnectionService::getConnection($connectionId);
        if (!$connection) {
            throw new \RuntimeException('The selected Google Ads connection could not be found.');
        }

        $config = get_option('plover_crm_google_config', []);
        $developerToken = trim((string) ($config['developer_token'] ?? ''));
        if ($developerToken === '') {
            throw new \RuntimeException('The Google Ads developer token is not configured.');
        }

        $service = new GoogleAdsService();
        $result = $service->createOfflineConversionAction(
            $developerToken,
            (string) $connection->customer_id,
            $stageName,
            !empty($connection->manager_id) ? (string) $connection->manager_id : null
        );

        $resourceName = (string) ($result['resourceName'] ?? '');
        if ($resourceName === '' || !preg_match('/conversionActions\/(\d+)$/', $resourceName, $matches)) {
            throw new \RuntimeException('Google Ads did not return a valid conversion action.');
        }

        return [
            'id' => $matches[1],
            'name' => $stageName,
        ];
    }

    public static function resolveStageName(string $stageId): string
    {
        $normalizedStageId = sanitize_text_field($stageId);
        if ($normalizedStageId === '') {
            throw new \RuntimeException('A target stage is required.');
        }

        try {
            $crm = Plugin::getInstance()->getContainer()->get('crm');
            $fields = $crm->getAllCustomFields();

            foreach ($fields as $field) {
                if (($field['slug'] ?? '') !== 'stage-plover-crm' || empty($field['options'])) {
                    continue;
                }

                foreach ((array) $field['options'] as $option) {
                    if ((string) $option === $normalizedStageId) {
                        return (string) $option;
                    }
                }

                break;
            }
        } catch (\Throwable $e) {
            throw new \RuntimeException('The selected stage could not be validated.');
        }

        throw new \RuntimeException('The selected stage is no longer available.');
    }
}
