<?php
require_once __DIR__ . '/../web-files/libs/valkey-mgmt.php';

$mgr = new ValkeyMgr(null); // null DB is fine for pure-function tests
$fails = 0;

// Cache-only mode
$conf = $mgr->generate_config(['memory_mb' => 128, 'mode' => 'cache', 'eviction_policy' => 'allkeys-lru']);
$must_have = ['maxmemory 128mb', 'maxmemory-policy allkeys-lru', 'save ""', 'appendonly no', 'protected-mode no'];
foreach ($must_have as $needle) {
    if (strpos($conf, $needle) === false) { fwrite(STDERR, "FAIL cache: missing '$needle'\n"); $fails++; }
}
if (strpos($conf, 'save 300') !== false) { fwrite(STDERR, "FAIL cache: must not contain 'save 300'\n"); $fails++; }

// Snapshot mode
$conf = $mgr->generate_config(['memory_mb' => 256, 'mode' => 'snapshot', 'eviction_policy' => 'noeviction']);
$must_have = ['maxmemory 256mb', 'maxmemory-policy noeviction', 'save 300 1', 'dir /data', 'dbfilename dump.rdb'];
foreach ($must_have as $needle) {
    if (strpos($conf, $needle) === false) { fwrite(STDERR, "FAIL snap: missing '$needle'\n"); $fails++; }
}

// Eviction-policy whitelist
$valid = ['allkeys-lru','allkeys-lfu','volatile-lru','volatile-lfu','volatile-ttl','volatile-random','allkeys-random','noeviction'];
foreach ($valid as $p) {
    if (!$mgr->is_valid_eviction_policy($p)) { fwrite(STDERR, "FAIL whitelist rejects '$p'\n"); $fails++; }
}
if ($mgr->is_valid_eviction_policy('; rm -rf /')) { fwrite(STDERR, "FAIL whitelist accepts injection\n"); $fails++; }

// Mode whitelist
if (!$mgr->is_valid_mode('cache') || !$mgr->is_valid_mode('snapshot')) { fwrite(STDERR, "FAIL mode valid\n"); $fails++; }
if ($mgr->is_valid_mode('hybrid')) { fwrite(STDERR, "FAIL mode invalid accepted\n"); $fails++; }

// Memory band — accepts 32 and 256 (boundaries), rejects 16 and 512.
$band_cases = [
    [32,  true],   // lower bound
    [256, true],   // upper bound
    [128, true],   // mid
    [16,  false],  // below band
    [31,  false],
    [257, false],
    [512, false],
];
foreach ($band_cases as $c) {
    list($mb, $should_accept) = $c;
    $accepted = true;
    try {
        $mgr->generate_config(['memory_mb' => $mb, 'mode' => 'cache', 'eviction_policy' => 'allkeys-lru']);
    } catch (InvalidArgumentException $e) {
        $accepted = false;
    }
    if ($accepted !== $should_accept) {
        fwrite(STDERR, "FAIL band: memory_mb=$mb expected " . ($should_accept ? 'accept' : 'reject') . "\n");
        $fails++;
    }
}

if ($fails === 0) { echo "PASS: config gen & whitelists\n"; exit(0); }
exit(1);
