<?php

namespace FleekDash\Controllers\Stats;

use FleekDash\Core\CacheInvalidationManager;

if (!\function_exists('fleekdash_log_debug')) {
    require_once FLEEKDASH_PLUGIN_DIR . 'includes/Core/debug-helpers.php';
}

/**
 * Stats Cache
 *
 * Handles caching for statistics data
 *
 * @package FleekDash\Controllers\Stats
 * @since 2.2.0 - Refactored to use CacheInvalidationManager for deadlock-safe,
 *                debounced cache invalidation.
 */
class StatsCache
{
    /**
     * Prefix for transients stored in wp_options so uninstall can match them
     * (object cache group {@see self::OBJECT_CACHE_GROUP} already isolates keys).
     */
    private const TRANSIENT_KEY_PREFIX = 'fleekdash_stats_';

    private const OBJECT_CACHE_GROUP = 'fleekdash_stats';

    /**
     * Register cache invalidation hooks
     *
     * @since 2.2.0 - Hooks are now handled centrally by CacheInvalidationManager
     *                to prevent duplicate invalidations and deadlocks.
     *                This method is kept for backward compatibility but
     *                no longer registers duplicate hooks.
     */
    public static function registerInvalidationHooks(): void
    {
        // IMPORTANT: Cache invalidation hooks are now handled centrally
        // by CacheInvalidationManager::setupHooks() which is called
        // from AnalyticsCacheService::setup_smart_invalidation().
        //
        // This prevents duplicate hook registrations that cause:
        // 1. Multiple DELETE queries running concurrently
        // 2. Database deadlocks when multiple hooks fire on the same event
        //
        // The CacheInvalidationManager provides:
        // - Debouncing (only one invalidation per request)
        // - Deadlock-safe queries with retry mechanism
        // - Consolidated batch deletes
        //
        // DO NOT register hooks here - they are already registered.
    }

    /**
     * Invalidate stats caches when content changes
     *
     * @since 2.2.0 - Delegates to CacheInvalidationManager for deadlock-safe,
     *                debounced invalidation. This method is kept for backward
     *                compatibility but uses the centralized manager internally.
     */
    public static function invalidateStatsCache(): void
    {
        // Delegate to centralized manager (handles debouncing and deadlock safety)
        CacheInvalidationManager::getInstance()->invalidateStatsCache();

        // Update frontend cache invalidation flag
        \update_option('fleekdash_invalidate_frontend_cache', time(), false);
    }

    /**
     * Get from cache (object cache first, fallback to transients)
     *
     * @param string $key Cache key
     * @return mixed|false Cached value or false
     */
    public function get(string $key)
    {
        if (function_exists('wp_cache_get')) {
            $value = wp_cache_get($key, self::OBJECT_CACHE_GROUP);
            if ($value !== false) {
                if (function_exists('fleekdash_is_debug_logging_active') && fleekdash_is_debug_logging_active()) {
                    fleekdash_log_debug("[StatsCache] HIT (object cache): {$key}");
                }
                return $value;
            }
        }

        $transientKey = self::TRANSIENT_KEY_PREFIX . $key;
        $value = \get_transient($transientKey);
        if ($value !== false && $value !== null) {
            if (function_exists('fleekdash_is_debug_logging_active') && fleekdash_is_debug_logging_active()) {
                fleekdash_log_debug("[StatsCache] HIT (transient): {$transientKey}");
            }
            return $value;
        }

        if (function_exists('fleekdash_is_debug_logging_active') && fleekdash_is_debug_logging_active()) {
            fleekdash_log_debug("[StatsCache] MISS: {$transientKey}");
        }
        return false;
    }

    /**
     * Set cache (object cache and transients)
     *
     * @param string $key Cache key
     * @param mixed $value Value to cache
     * @param int $ttl Time to live in seconds
     */
    public function set(string $key, $value, int $ttl): void
    {
        if (function_exists('wp_cache_set')) {
            wp_cache_set($key, $value, self::OBJECT_CACHE_GROUP, $ttl);
        }
        \set_transient(self::TRANSIENT_KEY_PREFIX . $key, $value, $ttl);

        if (function_exists('fleekdash_is_debug_logging_active') && fleekdash_is_debug_logging_active()) {
            fleekdash_log_debug("[StatsCache] SET: " . self::TRANSIENT_KEY_PREFIX . "{$key} (ttl={$ttl}s)");
        }
    }
}
