#!/usr/bin/env bash
# Tests para mas_syn2mas_migration
# Verifica arg parsing sin conectar al VPS real.
set -uo pipefail

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

PASS=0
FAIL=0

assert_exit() {
    local test_name="$1" expected_exit="$2"
    shift 2
    local actual_exit=0
    set +e
    "$@" >/dev/null 2>&1
    actual_exit=$?
    set -e
    if [[ "$actual_exit" == "$expected_exit" ]]; then
        echo "PASS: $test_name"
        ((PASS++)) || true
    else
        echo "FAIL: $test_name — expected exit $expected_exit, got $actual_exit"
        ((FAIL++)) || true
    fi
}

assert_stdout_contains() {
    local test_name="$1" needle="$2"
    shift 2
    local output actual_exit=0
    set +e
    output=$("$@" 2>/dev/null)
    actual_exit=$?
    set -e
    if echo "$output" | grep -q "$needle"; then
        echo "PASS: $test_name"
        ((PASS++)) || true
    else
        echo "FAIL: $test_name — expected stdout to contain '$needle', got: $output"
        ((FAIL++)) || true
    fi
}

# Test: aborta con error cuando faltan args obligatorios
assert_exit "aborta con error cuando faltan args obligatorios" 1 \
    mas_syn2mas_migration

# Test: help no devuelve error
assert_exit "help no devuelve error" 0 \
    mas_syn2mas_migration --help

# Test: argumento desconocido retorna exit 1
assert_exit "argumento desconocido retorna exit 1" 1 \
    mas_syn2mas_migration --unknown-flag

# Test: max-conflicts invalido retorna exit 1
assert_exit "max-conflicts invalido retorna exit 1" 1 \
    mas_syn2mas_migration \
        --ssh-host fake-host \
        --mas-container fake-container \
        --synapse-config-path /fake/homeserver.yaml \
        --log-dir "/tmp/test_mas_migration_$$" \
        --max-conflicts "not-a-number"

# Test: help emite JSON valido con status=help
assert_stdout_contains "help emite JSON con status help" '"status":"help"' \
    mas_syn2mas_migration --help

# Test: falta --ssh-host emite JSON con status=error
assert_stdout_contains "falta ssh-host emite JSON error" '"status":"error"' \
    mas_syn2mas_migration \
        --mas-container fake-container \
        --synapse-config-path /fake/homeserver.yaml \
        --log-dir "/tmp/test_mas_migration_$$"

# Test: falta --log-dir emite JSON con status=error
assert_stdout_contains "falta log-dir emite JSON error" '"status":"error"' \
    mas_syn2mas_migration \
        --ssh-host fake-host \
        --mas-container fake-container \
        --synapse-config-path /fake/homeserver.yaml

# Limpieza
rm -rf "/tmp/test_mas_migration_$$" 2>/dev/null || true

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