<?php
namespace Mamba\Support;

use Exception;

/**
 * Cache Namespace Management for Safe Invalidation
 */
final class CacheNamespace {
    
    private static $cache = []; // In-request memoization
    
    /**
     * Get current namespace for a cache group
     */
    public static function getNamespace(string $group): string {
        if (isset(self::$cache[$group])) {
            return self::$cache[$group];
        }
        
        // Safety check for WordPress functions
        if (!function_exists('get_option')) {
            return '1';
        }
        
        try {
            $opt_key = "mamba_ns_$group";
            $ns = get_option($opt_key, '1');
            return self::$cache[$group] = (string) $ns;
        } catch (Exception $e) {
            return '1';
        }
    }
    
    /**
     * Bump namespace to invalidate all cached data for a group
     */
    public static function bumpNamespace(string $group): void {
        // Safety check for WordPress functions
        if (!function_exists('get_option') || !function_exists('update_option')) {
            return;
        }
        
        try {
            $opt_key = "mamba_ns_$group";
            $new = (string) ((int) get_option($opt_key, '1') + 1);
            update_option($opt_key, $new, false); // false keeps autoload='no'
            self::$cache[$group] = $new;
        } catch (Exception $e) {
            // Silently fail - namespace bump is not critical
        }
    }
    
    /**
     * Get all available cache groups
     */
    public static function getGroups(): array {
        return [
            'mamba_store_api' => 'Store API Cache',
            'mamba_tags' => 'Tag Markers',
            'mamba_stats' => 'Statistics',
            'mamba_cart_fragments' => 'Cart Fragments'
        ];
    }
}
