<?php

namespace WPD_Platform\Services;

use WPD_Platform\Plugin;
use WPD_Platform\Singleton;
use WPD_Platform\Utils\Logger;

/**
 * TriggerDispatcher class
 *
 * Listens to integration trigger events and dispatches them to CHQ.
 * This enables automation workflows in CHQ to react to WordPress events.
 *
 * @package WPD_Platform\Services
 */
class TriggerDispatcher extends Singleton
{
    /**
     * Initialize the trigger dispatcher
     *
     * @return void
     */
    public function init(): void
    {
        // Listen for trigger events from the SDK
        add_action('dollie_trigger_fired', [$this, 'handle_trigger_fired'], 10, 2);
    }

    /**
     * Handle a fired trigger and dispatch it to CHQ
     *
     * @param string $trigger The trigger identifier (e.g., 'wordpress/user_login')
     * @param array  $context The trigger context data
     *
     * @return void
     */
    public function handle_trigger_fired(string $trigger, array $context): void
    {
        // Don't dispatch if site is not connected
        if (!Plugin::instance()->get_host()->is_connected()) {
            Logger::debug('Trigger not dispatched - site not connected: ' . $trigger, 'TriggerDispatcher');
            return;
        }

        // Build the payload
        $payload = [
            'trigger' => $trigger,
            'context' => $this->sanitize_context($context),
        ];

        // Log if debugging is enabled
        Logger::debug('Dispatching trigger to CHQ: ' . $trigger, 'TriggerDispatcher');

        // Send to CHQ
        $response = ChqApiClient::instance()->post('trigger-fired', $payload);

        // Log the result
        if (ChqApiClient::instance()->is_success($response)) {
            Logger::debug('Trigger dispatched successfully: ' . $trigger, 'TriggerDispatcher');
        } else {
            $error_message = is_wp_error($response)
                ? $response->get_error_message()
                : 'HTTP ' . wp_remote_retrieve_response_code($response);
            Logger::error('Failed to dispatch trigger: ' . $trigger . ' - ' . $error_message, 'TriggerDispatcher');
        }
    }

    /**
     * Sanitize context data before sending to CHQ
     *
     * Removes sensitive data and ensures the context is JSON-serializable.
     *
     * @param array $context The raw context data
     *
     * @return array The sanitized context
     */
    protected function sanitize_context(array $context): array
    {
        $sanitized = [];
        foreach ($context as $key => $value) {

            // Recursively sanitize arrays
            if (is_array($value)) {
                $sanitized[$key] = $this->sanitize_context($value);
            } elseif (is_object($value)) {
                // Convert objects to arrays for JSON serialization
                $sanitized[$key] = $this->sanitize_context((array) $value);
            } elseif (is_scalar($value) || is_null($value)) {
                $sanitized[$key] = $value;
            }
            // Skip non-serializable values (resources, closures, etc.)
        }

        return $sanitized;
    }
}
