#!/bin/bash

# Simple test script to verify subscription limit enforcement and rate limiting
# This script tests that subscription limits are enforced early

set -e

RELAY_URL="ws://127.0.0.1:8888"

echo "=== Subscription Limit Test ==="
echo "[INFO] Testing relay at: $RELAY_URL"
echo "[INFO] Note: This test assumes default subscription limits (max 25 per client)"
echo ""

# Test basic connectivity first
echo "=== Test 1: Basic Connectivity ==="
echo "[INFO] Testing basic WebSocket connection..."

# Send a simple REQ message
response=$(echo '["REQ","basic_test",{}]' | timeout 5 websocat -n1 "$RELAY_URL" 2>/dev/null || echo "TIMEOUT")

if echo "$response" | grep -q "EOSE\|EVENT\|NOTICE"; then
    echo "[PASS] Basic connectivity works"
else
    echo "[FAIL] Basic connectivity failed. Response: $response"
    exit 1
fi
echo ""

# Test subscription limits
echo "=== Test 2: Subscription Limit Enforcement ==="
echo "[INFO] Testing subscription limits by creating multiple subscriptions..."

success_count=0
limit_hit=false

# Create multiple subscriptions within a single WebSocket connection
echo "[INFO] Creating multiple subscriptions within a single connection..."

# Build a sequence of REQ messages
req_messages=""
for i in {1..30}; do
    sub_id="limit_test_$i"
    req_messages="${req_messages}[\"REQ\",\"$sub_id\",{}]\n"
done

# Send all messages through a single websocat connection and save to temp file
temp_file=$(mktemp)
echo -e "$req_messages" | timeout 10 websocat -B 1048576 "$RELAY_URL" 2>/dev/null > "$temp_file" || echo "TIMEOUT" >> "$temp_file"

# Parse the response to check for subscription limit enforcement
subscription_count=0
while read -r line; do
    if [[ "$line" == *"CLOSED"* && "$line" == *"exceeded"* ]]; then
        echo "[INFO] Hit subscription limit at subscription $((subscription_count + 1))"
        limit_hit=true
        break
    elif [[ "$line" == *"EOSE"* ]]; then
        subscription_count=$((subscription_count + 1))
    fi
done < "$temp_file"

success_count=$subscription_count

# Clean up temp file
rm -f "$temp_file"

if [ "$limit_hit" = true ]; then
    echo "[PASS] Subscription limit enforcement working (limit hit after $success_count subscriptions)"
else
    echo "[WARN] Subscription limit not hit after 30 attempts"
fi
echo ""

echo "=== Test Complete ==="