#!/usr/bin/env bash
# Valkey integration smoke test — runs on the WHP server itself.
# Exercises the full enable / ping / SET / GET / isolation / disable / teardown cycle.
set -euo pipefail

CUSTOMER="${CUSTOMER:-valkey-qa}"

echo "[1/7] Ensure test customer exists in whp.client_allowances: $CUSTOMER"
mysql whp -e "INSERT IGNORE INTO whp.client_allowances (username) VALUES ('$CUSTOMER')"

echo "[2/7] Enable Valkey (cache mode, 64 MB)"
php -r '
require_once "/docker/whp/web/configs/config.php";
require_once "/docker/whp/web/libs/mysqlmgmt.php";
require_once "/docker/whp/web/libs/valkey-mgmt.php";
$db = (new mysqlmgmt())->getMySQLConnection();
$vk = new ValkeyMgr($db);
print_r($vk->enable("'"$CUSTOMER"'", ["memory_mb"=>64,"mode"=>"cache","eviction_policy"=>"allkeys-lru"], []));
'

echo "[3/7] PING"
docker exec "valkey-cust-$CUSTOMER" valkey-cli PING | grep -q PONG
echo "   OK"

echo "[4/7] SET + GET"
docker exec "valkey-cust-$CUSTOMER" valkey-cli SET testkey hello >/dev/null
out=$(docker exec "valkey-cust-$CUSTOMER" valkey-cli GET testkey)
[ "$out" = "hello" ] || { echo "FAIL: got '$out'"; exit 1; }
echo "   OK"

echo "[5/7] Isolation — disposable container on client-net cannot resolve 'valkey'"
docker run --rm --network client-net alpine sh -c "getent hosts valkey || echo NOT_RESOLVED" | grep -q NOT_RESOLVED
echo "   OK"

echo "[6/7] Disable"
php -r '
require_once "/docker/whp/web/configs/config.php";
require_once "/docker/whp/web/libs/mysqlmgmt.php";
require_once "/docker/whp/web/libs/valkey-mgmt.php";
$db = (new mysqlmgmt())->getMySQLConnection();
$vk = new ValkeyMgr($db);
print_r($vk->disable("'"$CUSTOMER"'", []));
'

echo "[7/7] Teardown check — container, network, and /home dir gone"
# Container / network are expected to be gone. Invert the check via explicit exit
# code rather than piping through grep — pipefail would otherwise propagate the
# expected non-zero exit from docker inspect and trigger a false FAIL.
if docker inspect "valkey-cust-$CUSTOMER" >/dev/null 2>&1; then echo "FAIL: container still exists"; exit 1; fi
if docker network inspect "cust-$CUSTOMER-valkey-net" >/dev/null 2>&1; then echo "FAIL: network still exists"; exit 1; fi
[ ! -d "/home/$CUSTOMER/valkey" ] || { echo "FAIL: /home/$CUSTOMER/valkey still exists"; exit 1; }

echo "ALL PASS"
