#!/bin/bash

# Test for invalid kind filter validation and NOTICE response
# This test verifies that the relay properly responds with a NOTICE message
# when a REQ contains an invalid kind value (> 65535 per NIP-01)

RELAY_URL="ws://localhost:8888"
TEST_NAME="Invalid Kind Filter Test"

echo "=========================================="
echo "$TEST_NAME"
echo "=========================================="
echo ""

# Test 1: Send REQ with invalid kind (99999 > 65535)
echo "Test 1: REQ with invalid kind 99999 (should receive NOTICE)"
echo "---"

RESPONSE=$(timeout 3 websocat "$RELAY_URL" <<EOF
["REQ","test-invalid-kind",{"kinds":[99999],"limit":0}]
EOF
)

echo "Response: $RESPONSE"

if echo "$RESPONSE" | grep -q "NOTICE"; then
    echo "✓ PASS: Received NOTICE for invalid kind"
    if echo "$RESPONSE" | grep -qi "kind"; then
        echo "✓ PASS: NOTICE mentions kind validation"
    else
        echo "⚠ WARNING: NOTICE doesn't mention kind (but NOTICE was sent)"
    fi
else
    echo "✗ FAIL: No NOTICE received for invalid kind"
    exit 1
fi

echo ""

# Test 2: Send REQ with valid kind (should receive EOSE)
echo "Test 2: REQ with valid kind 1 (should receive EOSE)"
echo "---"

RESPONSE=$(timeout 3 websocat "$RELAY_URL" <<EOF
["REQ","test-valid-kind",{"kinds":[1],"limit":0}]
EOF
)

echo "Response: $RESPONSE"

if echo "$RESPONSE" | grep -q "EOSE"; then
    echo "✓ PASS: Received EOSE for valid kind"
else
    echo "✗ FAIL: No EOSE received for valid kind"
    exit 1
fi

echo ""

# Test 3: Send REQ with kind at boundary (65535 - should be valid)
echo "Test 3: REQ with boundary kind 65535 (should receive EOSE)"
echo "---"

RESPONSE=$(timeout 3 websocat "$RELAY_URL" <<EOF
["REQ","test-boundary-kind",{"kinds":[65535],"limit":0}]
EOF
)

echo "Response: $RESPONSE"

if echo "$RESPONSE" | grep -q "EOSE"; then
    echo "✓ PASS: Received EOSE for boundary kind 65535"
else
    echo "✗ FAIL: No EOSE received for boundary kind"
    exit 1
fi

echo ""

# Test 4: Send REQ with kind just over boundary (65536 - should receive NOTICE)
echo "Test 4: REQ with over-boundary kind 65536 (should receive NOTICE)"
echo "---"

RESPONSE=$(timeout 3 websocat "$RELAY_URL" <<EOF
["REQ","test-over-boundary",{"kinds":[65536],"limit":0}]
EOF
)

echo "Response: $RESPONSE"

if echo "$RESPONSE" | grep -q "NOTICE"; then
    echo "✓ PASS: Received NOTICE for over-boundary kind"
else
    echo "✗ FAIL: No NOTICE received for over-boundary kind"
    exit 1
fi

echo ""
echo "=========================================="
echo "All tests passed!"
echo "=========================================="
