#!/usr/bin/env bash
# Tests para check_service_health_via_ssh
set -euo pipefail

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
source "$SCRIPT_DIR/check_service_health_via_ssh.sh"

PASS=0
FAIL=0

assert_contains() {
    local test_name="$1" needle="$2" haystack="$3"
    if echo "$haystack" | grep -qF "$needle"; then
        echo "PASS: $test_name"
        PASS=$((PASS+1))
    else
        echo "FAIL: $test_name — expected to contain '$needle'"
        echo "      got: $haystack"
        FAIL=$((FAIL+1))
    fi
}

assert_not_contains() {
    local test_name="$1" needle="$2" haystack="$3"
    if ! echo "$haystack" | grep -qF "$needle"; then
        echo "PASS: $test_name"
        PASS=$((PASS+1))
    else
        echo "FAIL: $test_name — expected NOT to contain '$needle'"
        echo "      got: $haystack"
        FAIL=$((FAIL+1))
    fi
}

# --- stub SSH: en vez de conectarse, lee el .env remoto fake (si el snippet lo
# referencia) y emite el http_code de la env var STUB_HTTP_CODE. Simula tanto el
# caso "curl exito" (solo http_code) como "curl fallo" (<rc>:<http_code>). ---
STUB=$(mktemp)
chmod +x "$STUB"
cat > "$STUB" <<'STUBEOF'
#!/usr/bin/env bash
# Stub de ssh para tests. Ignora flags -o ... y el host; el ultimo arg es el
# script remoto. Emite el codigo segun STUB_HTTP_CODE / STUB_CURL_RC.
code="${STUB_HTTP_CODE:-200}"
rc="${STUB_CURL_RC:-0}"
# Si el script remoto referencia un .env y STUB_TOKEN_EMPTY=1, simular token vacio.
if [[ "${STUB_TOKEN_EMPTY:-0}" == "1" ]]; then
    echo "000"
    exit 7
fi
if [[ "$rc" == "0" ]]; then
    echo "$code"
else
    echo "${rc}:${code}"
    exit 0
fi
STUBEOF
chmod +x "$STUB"

FAKE_ENV=$(mktemp)
cat > "$FAKE_ENV" <<'ENVEOF'
SOME_OTHER=foo
AGENTS_API_KEY=supersecret-token-123
ANOTHER=bar
ENVEOF

trap 'rm -f "$STUB" "$FAKE_ENV"' EXIT

# --- Test: service healthy con token desde .env remoto (200 esperado) ---
result=$(CHECK_HEALTH_SSH_BIN="$STUB" STUB_HTTP_CODE=200 \
    check_service_health_via_ssh om "http://127.0.0.1:8487/agent" \
    --token-from-env "$FAKE_ENV" AGENTS_API_KEY --expect-status 200) || true
assert_contains     "service healthy con token desde env remoto" '"healthy":true'  "$result"
assert_contains     "service healthy con token desde env remoto" '"http_code":200' "$result"
assert_contains     "service healthy con token desde env remoto" '"status":"ok"'   "$result"
assert_not_contains "service healthy con token desde env remoto" 'supersecret'     "$result"

# --- Test: service no healthy cuando http_code no coincide con expect-status ---
result=$(CHECK_HEALTH_SSH_BIN="$STUB" STUB_HTTP_CODE=503 STUB_CURL_RC=22 \
    check_service_health_via_ssh om "http://127.0.0.1:8487/agent" \
    --token-from-env "$FAKE_ENV" AGENTS_API_KEY --expect-status 200) || true
assert_contains "service no healthy con http_code 503" '"healthy":false' "$result"
assert_contains "service no healthy con http_code 503" '"http_code":503' "$result"

# --- Test: salida JSON nunca filtra el token ---
result=$(CHECK_HEALTH_SSH_BIN="$STUB" STUB_HTTP_CODE=200 \
    check_service_health_via_ssh om "http://127.0.0.1:9000/health" \
    --token literal-secret-xyz) || true
assert_not_contains "salida JSON nunca filtra el token" 'literal-secret-xyz' "$result"
assert_contains     "salida JSON nunca filtra el token" '"healthy":true'     "$result"

# --- Test: sin token y 2xx por defecto cuenta como healthy ---
result=$(CHECK_HEALTH_SSH_BIN="$STUB" STUB_HTTP_CODE=204 \
    check_service_health_via_ssh om "http://127.0.0.1:8080/ping") || true
assert_contains "sin token 2xx por defecto es healthy" '"healthy":true'  "$result"
assert_contains "sin token 2xx por defecto es healthy" '"http_code":204' "$result"

# --- Test: falta argumento obligatorio devuelve error de uso ---
set +e
err=$(check_service_health_via_ssh om 2>&1)
ec=$?
set -e
assert_contains "falta argumento obligatorio devuelve error de uso" 'uso:' "$err"
if [[ "$ec" -ne 0 ]]; then
    echo "PASS: falta argumento sale con codigo distinto de 0"
    PASS=$((PASS+1))
else
    echo "FAIL: falta argumento deberia salir != 0 (got $ec)"
    FAIL=$((FAIL+1))
fi

echo "---"
echo "Results: $PASS passed, $FAIL failed"
[[ $FAIL -eq 0 ]] || exit 1
