<?php

namespace CloudXM\SDK\Logging\Bridges;

final class WooCommerceLoggerBridge
{
    private static bool $booted = false;

    public static function boot(): void
    {
        if (self::$booted) {
            return;
        }
        self::$booted = true;

        // Allow enable/disable via constant or filter (default: on in dev)
        $enabled = defined('CXM_WC_LOG_MIRROR')
            ? (bool) CXM_WC_LOG_MIRROR
            : apply_filters('cloudxm_sdk_wc_log_mirror_enabled', self::defaultEnabled());

        if (!$enabled) {
            return;
        }

        // Prefer the canonical SDK-wide emission hook
        add_action('cloudxm_log_emitted', [__CLASS__, 'mirror'], 10, 3);

        // Back-compat with older central-logger hook name (if present)
        add_action('cloudxm_logger_mirrored', [__CLASS__, 'mirror'], 10, 3);
    }

    protected static function defaultEnabled(): bool
    {
        if (defined('WP_DEBUG') && WP_DEBUG) {
            return true;
        }
        if (defined('WP_ENVIRONMENT_TYPE') && WP_ENVIRONMENT_TYPE !== 'production') {
            return true;
        }
        return false; // off by default in prod
    }

    /**
     * @param string $level   e.g. DEBUG|INFO|NOTICE|WARN|ERROR
     * @param string $message event key, e.g. marlim.charge.created
     * @param array  $context structured context (already redacted by SDK)
     */
    public static function mirror(string $level, string $message, array $context): void
    {
        // Optional: allow products to veto mirroring
        if (!apply_filters('cloudxm_sdk_wc_log_should_mirror', true, $level, $message, $context)) {
            return;
        }

        // Extract plugin name from context (preferred) or message key
        $pluginSource = $context['plugin'] ?? self::extractPluginFromMessage($message);

        // Prefer Woo logger if available, else PHP error_log
        if (function_exists('wc_get_logger') && class_exists('WC_Logger')) {
            $wc = wc_get_logger();
            $wcLevel = match (strtoupper($level)) {
                'DEBUG' => 'debug',
                'INFO', 'NOTICE' => 'info',
                'WARN', 'WARNING' => 'warning',
                default => 'error',
            };

            // Keep the line compact; the SDK should already have redacted PII.
            $wc->log(
                $wcLevel,
                $message . ' ' . wp_json_encode($context, JSON_UNESCAPED_SLASHES),
                ['source' => $pluginSource]
            );
        } else {
            error_log('[' . $pluginSource . '] ' . $message . ' ' . wp_json_encode($context, JSON_UNESCAPED_SLASHES));
        }
    }

    /**
     * Extract plugin name from CloudXM message key
     */
    private static function extractPluginFromMessage(string $message): string
    {
        // CloudXM messages follow 'plugin.action.subaction' format
        $parts = explode('.', $message);
        return $parts[0] ?? 'cloudxm';
    }
}