<?php
namespace Mamba\Support;

use Exception;

/**
 * Universal Cache Adapter - Object Cache with File Fallback
 */
final class CacheAdapter {
    
    /**
     * Generate namespaced cache key
     */
    private static function key(string $key, string $group): string {
        // Safety check for required class
        if (!class_exists('\Mamba\Support\CacheNamespace')) {
            return 'mamba:v1:' . $group . ':' . $key;
        }
        
        return 'mamba:v' . CacheNamespace::getNamespace($group) . ':' . $group . ':' . $key;
    }
    
    /**
     * Get cached data
     */
    public static function get(string $key, string $group, $fallback = null) {
        // Safety check for required classes
        if (!class_exists('\Mamba\Support\ObjectCache') || !class_exists('\Mamba\Support\FileCache')) {
            return $fallback;
        }
        
        $k = self::key($key, $group);
        
        try {
            if (ObjectCache::hasPersistentCache()) {
                $result = wp_cache_get($k, $group);
                if ($result !== false) {
                    return $result;
                }
            }
        } catch (Exception $e) {
            // Fallback to file cache on any error
        }
        
        // Fallback to file cache
        return FileCache::get("$group/$k") ?? $fallback;
    }
    
    /**
     * Set cached data
     */
    public static function set(string $key, $value, string $group, int $ttl = 60): bool {
        // Safety check for required classes
        if (!class_exists('\Mamba\Support\ObjectCache') || !class_exists('\Mamba\Support\FileCache')) {
            return false;
        }
        
        $k = self::key($key, $group);
        
        try {
            if (ObjectCache::hasPersistentCache()) {
                return wp_cache_set($k, $value, $group, $ttl);
            }
        } catch (Exception $e) {
            // Fallback to file cache on any error
        }
        
        // Fallback to file cache
        return FileCache::set("$group/$k", $value, $ttl);
    }
    
    /**
     * Delete cached data
     */
    public static function delete(string $key, string $group): bool {
        // Safety check for required classes
        if (!class_exists('\Mamba\Support\ObjectCache') || !class_exists('\Mamba\Support\FileCache')) {
            return false;
        }
        
        $k = self::key($key, $group);
        
        try {
            if (ObjectCache::hasPersistentCache()) {
                wp_cache_delete($k, $group);
            }
        } catch (Exception $e) {
            // Continue with file cache deletion
        }
        
        // Also delete from file cache
        return FileCache::delete("$group/$k");
    }
    
    /**
     * Increment counter (for stats)
     */
    public static function increment(string $key, string $group, int $value = 1): int {
        // Safety check for required classes
        if (!class_exists('\Mamba\Support\ObjectCache') || !class_exists('\Mamba\Support\FileCache')) {
            return 0;
        }
        
        $k = self::key($key, $group);
        
        try {
            if (ObjectCache::hasPersistentCache()) {
                $result = wp_cache_incr($k, $value, $group);
                if ($result === false) {
                    // Seed the key once for increment-capable backends
                    wp_cache_add($k, 0, $group);
                    $result = wp_cache_incr($k, $value, $group);
                }
                if ($result !== false) {
                    return (int)$result;
                }
            }
        } catch (Exception $e) {
            // Fallback to file cache increment
        }
        
        // Only then use file fallback
        return FileCache::increment("$group/$k", $value);
    }
    
    /**
     * Clear all cached data for a group
     */
    public static function clearGroup(string $group): void {
        // Safety check for required classes
        if (!class_exists('\Mamba\Support\CacheNamespace') || !class_exists('\Mamba\Support\FileCache')) {
            return;
        }
        
        // Bump namespace to invalidate all keys
        CacheNamespace::bumpNamespace($group);
        
        // Also clear file cache for this group
        FileCache::clearGroup($group);
    }
    
    /**
     * Clear all cached data (hard flush) - DISABLED FOR PRODUCTION SAFETY
     * 
     * This method has been disabled to prevent production issues where wp_cache_flush()
     * would clear ALL object cache data, affecting other plugins and causing performance issues.
     */
    public static function clearAll(): void {
        // DISABLED: This method is disabled for production safety
        // wp_cache_flush() clears ALL object cache data, which can cause:
        // - Performance issues (thundering herd effect)
        // - Other plugins losing their cache
        // - Site slowdowns in production
        
        // Only clear file cache as a safe fallback
        if (class_exists('\Mamba\Support\FileCache')) {
            FileCache::clearAll();
        }
        
        // Log the attempt for debugging
        if (defined('WP_DEBUG') && WP_DEBUG) {
            error_log('Mamba: clearAll() called but disabled for production safety. Use clearGroup() instead.');
        }
    }
}
