<?php
if (php_sapi_name() !== 'cli') {
    http_response_code(403);
    exit('Access denied.');
}

require_once dirname(__DIR__) . '/app/bootstrap.php';

use App\Core\Cache;
use App\Core\Env;

echo "=== Starting Redis Cache Verification Tests ===\n\n";

// Test 1: Fallback when Redis is disabled
echo "1. Testing fallback with Redis disabled...\n";
putenv("REDIS_ENABLED=false");
$_ENV['REDIS_ENABLED'] = 'false';
$_SERVER['REDIS_ENABLED'] = 'false';

$res = Cache::set('test_key', 'test_val', 10);
echo "   Set result: " . ($res ? "TRUE" : "FALSE (Fallback working)") . "\n";

$val = Cache::get('test_key');
echo "   Get result: " . ($val === null ? "NULL (Fallback working)" : $val) . "\n";

$rememberVal = Cache::remember('remember_key', 10, function() {
    return 'computed_fallback_val';
});
echo "   Remember callback result: " . $rememberVal . " (Expected: computed_fallback_val)\n";

// Test 2: Testing with Redis enabled (if phpredis is available)
if (class_exists('\Redis')) {
    echo "\n2. Redis extension found. Testing connection if enabled...\n";
    putenv("REDIS_ENABLED=true");
    $_ENV['REDIS_ENABLED'] = 'true';
    $_SERVER['REDIS_ENABLED'] = 'true';
    putenv("REDIS_HOST=127.0.0.1");
    $_ENV['REDIS_HOST'] = '127.0.0.1';
    $_SERVER['REDIS_HOST'] = '127.0.0.1';
    putenv("REDIS_PORT=6379");
    $_ENV['REDIS_PORT'] = '6379';
    $_SERVER['REDIS_PORT'] = '6379';

    // Reset static state using reflection to allow re-testing
    try {
        $ref = new ReflectionClass(Cache::class);
        $connAttempted = $ref->getProperty('connectionAttempted');
        $connAttempted->setAccessible(true);
        $connAttempted->setValue(null, false);
        
        $clientProp = $ref->getProperty('client');
        $clientProp->setAccessible(true);
        $clientProp->setValue(null, null);

        $res = Cache::set('test_cache_key', ['hello' => 'world'], 30);
        if ($res) {
            echo "   ✅ Successfully set value in Redis.\n";
            $val = Cache::get('test_cache_key');
            if (isset($val['hello']) && $val['hello'] === 'world') {
                echo "   ✅ Successfully retrieved value from Redis: " . json_encode($val) . "\n";
            } else {
                echo "   ❌ Failed to get correct value from Redis.\n";
            }

            // Verify prefixing using a direct native Redis connection
            $nativeRedis = new \Redis();
            try {
                if ($nativeRedis->connect(Env::get('REDIS_HOST', '127.0.0.1'), (int)Env::get('REDIS_PORT', 6379), 1.0)) {
                    $nativeVal = $nativeRedis->get('nabeh:test_cache_key');
                    if ($nativeVal) {
                        echo "   ✅ Verified Prefixing: Native Redis key 'nabeh:test_cache_key' exists and has value: " . $nativeVal . "\n";
                    } else {
                        echo "   ❌ Prefixing test failed: key not found in native Redis.\n";
                    }
                    $nativeRedis->close();
                }
            } catch (\Exception $ex) {
                echo "   ℹ️ Native verification connection skipped/failed: " . $ex->getMessage() . "\n";
            }

            Cache::delete('test_cache_key');
        } else {
            echo "   ℹ️ Redis server is not running or unreachable (Fallback triggered, test completed successfully).\n";
        }
    } catch (\Exception $e) {
        echo "   Reflection or execution error: " . $e->getMessage() . "\n";
    }
} else {
    echo "\n2. Redis extension (phpredis) not installed. Native database fallback remains active.\n";
}

echo "\n=== Redis Caching Tests Completed ===\n";
