<?php

namespace PloverCRM\Modules\Automations\Services;

use PloverCRM\Core\Container;
use PloverCRM\Core\Services\PlaceholderService;
use PloverCRM\Modules\Integrations\Services\CurrencyService;
use PloverCRM\Modules\Integrations\Services\GoogleAdsConnectionService;
use PloverCRM\Modules\Integrations\Services\GoogleAdsLeadUploadStatusService;
use PloverCRM\Modules\Integrations\Services\MetaCapiConnectionService;

/**
 * Provides metadata needed by the standalone Automations app UI.
 */
class AutomationAppBootstrapService
{
    public static function build(Container $container): array
    {
        $placeholders = PlaceholderService::getAvailablePlaceholders();

        return [
            'templates' => array_map(
                [AutomationApiSerializer::class, 'template'],
                AutomationTemplateRegistry::getTemplates()
            ),
            'placeholders' => $placeholders,
            'placeholderGroups' => self::groupPlaceholders($placeholders),
            'googleConnections' => array_map(
                [self::class, 'serializeGoogleConnection'],
                GoogleAdsConnectionService::getAllConnections(false)
            ),
            'metaConnections' => array_map(
                static fn($connection) => $connection->toPublicArray(),
                MetaCapiConnectionService::getAllConnections(false)
            ),
            'currencyOptions' => self::serializeCurrencyOptions(),
            'sourceOptions' => [
                ['value' => 'any', 'label' => 'Any source'],
                ['value' => 'Webhook', 'label' => 'Webhook'],
                ['value' => 'FluentForms', 'label' => 'FluentForms'],
            ],
            'metaEventOptions' => [
                ['value' => 'AddPaymentInfo', 'label' => 'Add Payment Info'],
                ['value' => 'AddToCart', 'label' => 'Add To Cart'],
                ['value' => 'AddToWishlist', 'label' => 'Add To Wishlist'],
                ['value' => 'CompleteRegistration', 'label' => 'Complete Registration'],
                ['value' => 'Contact', 'label' => 'Contact'],
                ['value' => 'CustomizeProduct', 'label' => 'Customize Product'],
                ['value' => 'Donate', 'label' => 'Donate'],
                ['value' => 'FindLocation', 'label' => 'Find Location'],
                ['value' => 'InitiateCheckout', 'label' => 'Initiate Checkout'],
                ['value' => 'Lead', 'label' => 'Lead'],
                ['value' => 'Purchase', 'label' => 'Purchase'],
                ['value' => 'Schedule', 'label' => 'Schedule'],
                ['value' => 'Search', 'label' => 'Search'],
                ['value' => 'StartTrial', 'label' => 'Start Trial'],
                ['value' => 'SubmitApplication', 'label' => 'Submit Application'],
                ['value' => 'Subscribe', 'label' => 'Subscribe'],
                ['value' => 'ViewContent', 'label' => 'View Content'],
                ['value' => 'Custom', 'label' => 'Custom'],
            ],
            'metaCustomParameterOptions' => [
                ['value' => 'value', 'label' => 'Value', 'dataType' => 'float'],
                ['value' => 'currency', 'label' => 'Currency', 'dataType' => 'string'],
                ['value' => 'content_name', 'label' => 'Content name', 'dataType' => 'string'],
                ['value' => 'content_category', 'label' => 'Content category', 'dataType' => 'string'],
                ['value' => 'content_ids', 'label' => 'Content IDs', 'dataType' => 'array'],
                ['value' => 'content_type', 'label' => 'Content type', 'dataType' => 'string'],
                ['value' => 'contents', 'label' => 'Contents', 'dataType' => 'array'],
                ['value' => 'num_items', 'label' => 'Number of items', 'dataType' => 'int'],
                ['value' => 'order_id', 'label' => 'Order ID', 'dataType' => 'string'],
                ['value' => 'predicted_ltv', 'label' => 'Predicted LTV', 'dataType' => 'float'],
                ['value' => 'search_string', 'label' => 'Search string', 'dataType' => 'string'],
                ['value' => 'status', 'label' => 'Status', 'dataType' => 'string'],
                ['value' => 'delivery_category', 'label' => 'Delivery category', 'dataType' => 'string'],
                ['value' => 'description', 'label' => 'Description', 'dataType' => 'string'],
                ['value' => 'level', 'label' => 'Level', 'dataType' => 'string'],
                ['value' => 'max_rating_value', 'label' => 'Max rating value', 'dataType' => 'int'],
                ['value' => 'payment_info_available', 'label' => 'Payment info available', 'dataType' => 'boolean'],
                ['value' => 'registration_method', 'label' => 'Registration method', 'dataType' => 'string'],
                ['value' => 'success', 'label' => 'Success', 'dataType' => 'boolean'],
                ['value' => 'Custom Parameter', 'label' => 'Custom parameter', 'dataType' => 'custom'],
            ],
        ];
    }

    private static function groupPlaceholders(array $placeholders): array
    {
        $grouped = [];

        foreach ($placeholders as $placeholder) {
            $group = (string) ($placeholder['group'] ?? 'Other');

            if (!isset($grouped[$group])) {
                $grouped[$group] = [];
            }

            $grouped[$group][] = [
                'key' => (string) ($placeholder['key'] ?? ''),
                'label' => (string) ($placeholder['label'] ?? ''),
            ];
        }

        return $grouped;
    }

    private static function serializeGoogleConnection($connection): array
    {
        return [
            'id' => (int) ($connection->id ?? 0),
            'customer_id' => (string) ($connection->customer_id ?? ''),
            'customer_name' => (string) ($connection->customer_name ?? ''),
            'status' => (string) ($connection->status ?? 'active'),
            'connected_at' => (int) ($connection->connected_at ?? 0),
            'connected_display' => method_exists($connection, 'getConnectedDisplay')
                ? $connection->getConnectedDisplay()
                : '',
            'lead_upload_status' => GoogleAdsLeadUploadStatusService::forConnection($connection, true),
        ];
    }

    private static function serializeCurrencyOptions(): array
    {
        $options = [];

        foreach (CurrencyService::getCurrencyOptions() as $code => $label) {
            $options[] = [
                'value' => $code,
                'label' => $label,
            ];
        }

        return $options;
    }
}
