#!/usr/bin/env bash
# Tests para mas_client_register
# No requiere SSH real — prueba paths locales (arg validation, --help, JSON output)

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"

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++))
    else
        echo "FAIL: $test_name — expected to contain '$needle', got: $haystack"
        ((FAIL++))
    fi
}

assert_json_parseable() {
    local test_name="$1" json="$2"
    if command -v jq &>/dev/null; then
        if echo "$json" | jq . >/dev/null 2>&1; then
            echo "PASS: $test_name"
            ((PASS++))
        else
            echo "FAIL: $test_name — output no es JSON valido: $json"
            ((FAIL++))
        fi
    else
        if [[ "$json" == \{* ]]; then
            echo "PASS: $test_name (jq no disponible, verificacion basica OK)"
            ((PASS++))
        else
            echo "FAIL: $test_name — output no parece JSON: $json"
            ((FAIL++))
        fi
    fi
}

# Test: help flag emite JSON parseable
# Cada invocacion en subshell aislada para no contaminar el runner con set -e del script fuente
bash "$SCRIPT_DIR/mas_client_register.sh" --help >/tmp/mas_test_help_$$ 2>/dev/null || true
output_help=$(cat /tmp/mas_test_help_$$ 2>/dev/null || true)
rm -f /tmp/mas_test_help_$$
assert_json_parseable "help flag emite JSON parseable" "$output_help"

# Test: args faltantes retornan JSON de error sin ssh
bash "$SCRIPT_DIR/mas_client_register.sh" >/tmp/mas_test_noargs_$$ 2>/dev/null || true
output_noargs=$(cat /tmp/mas_test_noargs_$$ 2>/dev/null || true)
rm -f /tmp/mas_test_noargs_$$
assert_json_parseable "args faltantes retornan JSON de error sin ssh" "$output_noargs"
assert_contains "args faltantes contienen status error" '"status":"error"' "$output_noargs"

# Test: jq disponible en host local
if command -v jq &>/dev/null; then
    echo "PASS: jq disponible en host local"
    ((PASS++))
else
    echo "FAIL: jq disponible en host local — instalar: apt install jq"
    ((FAIL++))
fi

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