#!/bin/bash

# Configuration Testing Suite for C-Relay
# Tests configuration management and persistence

set -e

# Configuration
RELAY_HOST="127.0.0.1"
RELAY_PORT="8888"

# Colors for output
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
NC='\033[0m' # No Color

# Test counters
TOTAL_TESTS=0
PASSED_TESTS=0
FAILED_TESTS=0

# Function to test configuration query
test_config_query() {
    local description="$1"
    local config_command="$2"
    local expected_pattern="$3"

    TOTAL_TESTS=$((TOTAL_TESTS + 1))

    echo -n "Testing $description... "

    # Create admin event for config query
    local admin_event
    admin_event=$(cat << EOF
{
  "kind": 23456,
  "content": "$(echo '["'"$config_command"'"]' | base64)",
  "tags": [["p", "relay_pubkey_placeholder"]],
  "created_at": $(date +%s),
  "pubkey": "admin_pubkey_placeholder",
  "sig": "signature_placeholder"
}
EOF
)

    # Send config query event
    local response
    response=$(echo "$admin_event" | timeout 10 websocat -B 1048576 ws://$RELAY_HOST:$RELAY_PORT 2>/dev/null | head -3 || echo 'TIMEOUT')

    if [[ "$response" == *"TIMEOUT"* ]]; then
        echo -e "${RED}FAILED${NC} - Connection timeout"
        FAILED_TESTS=$((FAILED_TESTS + 1))
        return 1
    fi

    if [[ "$response" == *"$expected_pattern"* ]]; then
        echo -e "${GREEN}PASSED${NC} - Config query successful"
        PASSED_TESTS=$((PASSED_TESTS + 1))
        return 0
    else
        echo -e "${RED}FAILED${NC} - Expected '$expected_pattern', got: $response"
        FAILED_TESTS=$((FAILED_TESTS + 1))
        return 1
    fi
}

# Function to test configuration setting
test_config_setting() {
    local description="$1"
    local config_command="$2"
    local config_value="$3"

    TOTAL_TESTS=$((TOTAL_TESTS + 1))

    echo -n "Testing $description... "

    # Create admin event for config setting
    local admin_event
    admin_event=$(cat << EOF
{
  "kind": 23456,
  "content": "$(echo '["'"$config_command"'","'"$config_value"'"]' | base64)",
  "tags": [["p", "relay_pubkey_placeholder"]],
  "created_at": $(date +%s),
  "pubkey": "admin_pubkey_placeholder",
  "sig": "signature_placeholder"
}
EOF
)

    # Send config setting event
    local response
    response=$(echo "$admin_event" | timeout 10 websocat -B 1048576 ws://$RELAY_HOST:$RELAY_PORT 2>/dev/null | head -3 || echo 'TIMEOUT')

    if [[ "$response" == *"TIMEOUT"* ]]; then
        echo -e "${RED}FAILED${NC} - Connection timeout"
        FAILED_TESTS=$((FAILED_TESTS + 1))
        return 1
    fi

    if [[ "$response" == *"OK"* ]]; then
        echo -e "${GREEN}PASSED${NC} - Config setting accepted"
        PASSED_TESTS=$((PASSED_TESTS + 1))
        return 0
    else
        echo -e "${RED}FAILED${NC} - Config setting rejected: $response"
        FAILED_TESTS=$((FAILED_TESTS + 1))
        return 1
    fi
}

# Function to test NIP-11 relay information
test_nip11_info() {
    TOTAL_TESTS=$((TOTAL_TESTS + 1))

    echo -n "Testing NIP-11 relay information... "

    local response
    response=$(curl -s -H "Accept: application/nostr+json" "http://$RELAY_HOST:$RELAY_PORT" 2>/dev/null || echo 'CURL_FAILED')

    if [[ "$response" == "CURL_FAILED" ]]; then
        echo -e "${RED}FAILED${NC} - HTTP request failed"
        FAILED_TESTS=$((FAILED_TESTS + 1))
        return 1
    fi

    if [[ "$response" == *"supported_nips"* ]] && [[ "$response" == *"software"* ]]; then
        echo -e "${GREEN}PASSED${NC} - NIP-11 information available"
        PASSED_TESTS=$((PASSED_TESTS + 1))
        return 0
    else
        echo -e "${RED}FAILED${NC} - NIP-11 information incomplete"
        FAILED_TESTS=$((FAILED_TESTS + 1))
        return 1
    fi
}

echo "=========================================="
echo "C-Relay Configuration Testing Suite"
echo "=========================================="
echo "Testing configuration management at ws://$RELAY_HOST:$RELAY_PORT"
echo ""

# Test basic connectivity
echo "=== Basic Connectivity Test ==="
test_config_query "Basic connectivity" "system_status" "OK"
echo ""

echo "=== NIP-11 Relay Information Tests ==="
test_nip11_info
echo ""

echo "=== Configuration Query Tests ==="
test_config_query "System status query" "system_status" "status"
test_config_query "Configuration query" "auth_query" "all"
echo ""

echo "=== Configuration Setting Tests ==="
test_config_setting "Relay description setting" "relay_description" "Test Relay"
test_config_setting "Max subscriptions setting" "max_subscriptions_per_client" "50"
test_config_setting "PoW difficulty setting" "pow_min_difficulty" "16"
echo ""

echo "=== Configuration Persistence Test ==="
echo -n "Testing configuration persistence... "
# Set a configuration value
test_config_setting "Set test config" "relay_description" "Persistence Test"

# Query it back
sleep 2
test_config_query "Verify persistence" "system_status" "Persistence Test"
echo ""

echo "=== Test Results ==="
echo "Total tests: $TOTAL_TESTS"
echo -e "Passed: ${GREEN}$PASSED_TESTS${NC}"
echo -e "Failed: ${RED}$FAILED_TESTS${NC}"

if [[ $FAILED_TESTS -eq 0 ]]; then
    echo -e "${GREEN}✓ All configuration tests passed!${NC}"
    echo "Configuration management is working correctly."
    exit 0
else
    echo -e "${RED}✗ Some configuration tests failed!${NC}"
    echo "Configuration management may have issues."
    exit 1
fi