<?php
/**
 * CDN Mirror Service
 *
 * Mirrors local cache purges to the configured CDN provider,
 * ensuring cache consistency between origin and edge.
 *
 * @package Mamba\Modules\CDN\Services
 * @since   1.0.0
 */

namespace Mamba\Modules\CDN\Services;

if ( ! defined( 'ABSPATH' ) ) {
    exit;
}

/**
 * Class CdnMirror
 *
 * Hooks into local cache purge actions and mirrors them to the
 * configured CDN provider for synchronized cache invalidation.
 *
 * @since 1.0.0
 */
final class CdnMirror {
    private static bool $initialized = false;
    
    /**
     * Initialize the CDN mirror
     */
    public static function init(): void {
        if (self::$initialized) return;
        
        // Hook into existing purge actions
        add_action('mamba_purge_tags', [__CLASS__, 'onPurgeTags'], 10, 1);
        add_action('mamba_purge_urls', [__CLASS__, 'onPurgeUrls'], 10, 2);
        add_action('mamba_purge_all', [__CLASS__, 'onPurgeAll'], 10, 0);
        
        // Hook into cache purged action
        add_action('mamba_cache_purged', [__CLASS__, 'onCachePurged'], 10, 0);
        
        self::$initialized = true;
    }
    
    /**
     * Handle tag purges
     */
    public static function onPurgeTags(array $tags): void {
        if (!Manager::isEnabled()) return;
        
        $provider = Manager::getProvider();
        if (!$provider) return;
        
        try {
            $result = $provider->purgeTags($tags);
            self::logAction('purge_tags', $result, ['tags' => $tags]);
        } catch (\Exception $e) {
            if (defined('WP_DEBUG') && WP_DEBUG) {
                error_log('Mamba CDN: Tag purge failed: ' . $e->getMessage());
            }
        }
    }
    
    /**
     * Handle URL purges
     */
    public static function onPurgeUrls(array $urls, array $headerCombos = []): void {
        if (!Manager::isEnabled()) return;
        
        $provider = Manager::getProvider();
        if (!$provider) return;
        
        // Generate header combinations for APO if needed
        if (empty($headerCombos) && Manager::getProviderName() === 'cloudflare') {
            $headerCombos = \Mamba\Modules\CDN\Services\Detectors::generateCloudflareHeaderCombos();
        }
        
        try {
            $result = $provider->purgeUrls($urls, $headerCombos);
            self::logAction('purge_urls', $result, ['urls' => $urls, 'header_combos' => $headerCombos]);
        } catch (\Exception $e) {
            if (defined('WP_DEBUG') && WP_DEBUG) {
                error_log('Mamba CDN: URL purge failed: ' . $e->getMessage());
            }
        }
    }
    
    /**
     * Handle full purges
     */
    public static function onPurgeAll(): void {
        if (!Manager::isEnabled()) return;
        
        $provider = Manager::getProvider();
        if (!$provider) return;
        
        try {
            $result = $provider->purgeAll();
            self::logAction('purge_all', $result);
        } catch (\Exception $e) {
            if (defined('WP_DEBUG') && WP_DEBUG) {
                error_log('Mamba CDN: Full purge failed: ' . $e->getMessage());
            }
        }
    }
    
    /**
     * Handle cache purged action
     */
    public static function onCachePurged(): void {
        // This is called when the internal cache is purged
        // We don't automatically trigger CDN purge here to avoid loops
        // CDN purges are handled by the specific purge actions above
    }
    
    /**
     * Log CDN actions for diagnostics
     */
    private static function logAction(string $action, Result $result, array $context = []): void {
        $log = get_option('mamba_cdn_actions', []);
        
        $entry = [
            'action' => $action,
            'success' => $result->isSuccess(),
            'message' => $result->getMessage(),
            'status_code' => $result->getStatusCode(),
            'timestamp' => time(),
            'provider' => Manager::getProviderName(),
            'context' => $context
        ];
        
        // Keep only last 100 entries
        $log[] = $entry;
        if (count($log) > 100) {
            $log = array_slice($log, -100);
        }
        
        update_option('mamba_cdn_actions', $log, false);
    }
    
    /**
     * Get CDN action log
     */
    public static function getActionLog(): array {
        return get_option('mamba_cdn_actions', []);
    }
    
    /**
     * Clear CDN action log
     */
    public static function clearActionLog(): void {
        delete_option('mamba_cdn_actions');
    }
}
