#!/bin/bash

# Ginxsom Admin Event Test Script
# Tests Kind 23458/23459 admin command system with NIP-44 encryption
#
# Prerequisites:
# - nak: https://github.com/fiatjaf/nak
# - curl
# - jq (for JSON parsing)
# - Server running with test keys from .test_keys

set -e

# Configuration
GINXSOM_URL="http://localhost:9001"
TEST_KEYS_FILE=".test_keys"

# Load test keys
if [[ ! -f "$TEST_KEYS_FILE" ]]; then
    echo "ERROR: $TEST_KEYS_FILE not found"
    echo "Run the server with --test-keys to generate test keys"
    exit 1
fi

source "$TEST_KEYS_FILE"

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

# Helper functions
log_info() {
    echo -e "${BLUE}[INFO]${NC} $1"
}

log_success() {
    echo -e "${GREEN}[SUCCESS]${NC} $1"
}

log_error() {
    echo -e "${RED}[ERROR]${NC} $1"
}

log_warning() {
    echo -e "${YELLOW}[WARNING]${NC} $1"
}

check_dependencies() {
    log_info "Checking dependencies..."

    for cmd in nak curl jq; do
        if ! command -v $cmd &> /dev/null; then
            log_error "$cmd is not installed"
            case $cmd in
                nak)
                    echo "Install from: https://github.com/fiatjaf/nak"
                    ;;
                jq)
                    echo "Install jq for JSON processing"
                    ;;
                curl)
                    echo "curl should be available in most systems"
                    ;;
            esac
            exit 1
        fi
    done

    log_success "All dependencies found"
}

# Create NIP-44 encrypted admin command event (Kind 23458)
create_admin_command_event() {
    local command="$1"
    local expiration=$(($(date +%s) + 3600))  # 1 hour from now
    
    log_info "Creating Kind 23458 admin command event..."
    log_info "Command: $command"
    
    # For now, we'll create the event structure manually since nak may not support NIP-44 encryption yet
    # The content should be NIP-44 encrypted JSON array: ["config_query"]
    # We'll use plaintext for initial testing and add encryption later
    
    local content="[\"$command\"]"
    
    # Create event with nak
    # Kind 23458 = admin command
    # Tags: p = server pubkey, expiration
    local event=$(nak event -k 23458 \
        -c "$content" \
        --tag p="$SERVER_PUBKEY" \
        --tag expiration="$expiration" \
        --sec "$ADMIN_PRIVKEY")
    
    echo "$event"
}

# Send admin command and parse response
send_admin_command() {
    local command="$1"
    
    log_info "=== Testing Admin Command: $command ==="
    
    # Create Kind 23458 event
    local event=$(create_admin_command_event "$command")
    
    if [[ -z "$event" ]]; then
        log_error "Failed to create admin event"
        return 1
    fi
    
    log_info "Event created successfully"
    echo "$event" | jq . || echo "$event"
    
    # Send to server
    log_info "Sending to POST $GINXSOM_URL/api/admin"
    
    local response=$(curl -s -w "\n%{http_code}" \
        -X POST \
        -H "Content-Type: application/json" \
        -d "$event" \
        "$GINXSOM_URL/api/admin")
    
    local http_code=$(echo "$response" | tail -n1)
    local body=$(echo "$response" | head -n-1)
    
    echo ""
    if [[ "$http_code" =~ ^2 ]]; then
        log_success "HTTP $http_code - Response received"
        echo "$body" | jq . 2>/dev/null || echo "$body"
        
        # Try to parse as Kind 23459 event
        local kind=$(echo "$body" | jq -r '.kind // empty' 2>/dev/null)
        if [[ "$kind" == "23459" ]]; then
            log_success "Received Kind 23459 response event"
            local response_content=$(echo "$body" | jq -r '.content // empty' 2>/dev/null)
            log_info "Response content (encrypted): $response_content"
            # TODO: Decrypt NIP-44 content to see actual response
        fi
    else
        log_error "HTTP $http_code - Request failed"
        echo "$body" | jq . 2>/dev/null || echo "$body"
        return 1
    fi
    
    echo ""
}

test_config_query() {
    log_info "=== Testing config_query Command ==="
    send_admin_command "config_query"
}

test_server_health() {
    log_info "=== Testing Server Health ==="
    
    local response=$(curl -s -w "\n%{http_code}" "$GINXSOM_URL/api/health")
    local http_code=$(echo "$response" | tail -n1)
    local body=$(echo "$response" | head -n-1)
    
    if [[ "$http_code" =~ ^2 ]]; then
        log_success "Server is healthy (HTTP $http_code)"
        echo "$body" | jq .
    else
        log_error "Server health check failed (HTTP $http_code)"
        echo "$body"
        return 1
    fi
    echo ""
}

main() {
    echo "=== Ginxsom Admin Event Test Suite ==="
    echo "Testing Kind 23458/23459 admin command system"
    echo ""
    
    log_info "Test Configuration:"
    log_info "  Admin Pubkey:  $ADMIN_PUBKEY"
    log_info "  Server Pubkey: $SERVER_PUBKEY"
    log_info "  Server URL:    $GINXSOM_URL"
    echo ""
    
    check_dependencies
    echo ""
    
    # Test server health first
    test_server_health
    
    # Test admin commands
    test_config_query
    
    echo ""
    log_success "Admin event testing complete!"
    echo ""
    log_warning "NOTE: NIP-44 encryption not yet implemented in test script"
    log_warning "Events are sent with plaintext command arrays for initial testing"
    log_warning "Production implementation will use full NIP-44 encryption"
}

# Allow sourcing for individual function testing
if [[ "${BASH_SOURCE[0]}" == "${0}" ]]; then
    main "$@"
fi