#!/bin/bash

# Simple comprehensive auth test
SERVER_URL="http://localhost:9001"
UPLOAD_ENDPOINT="${SERVER_URL}/upload"
DB_PATH="../db/ginxsom.db"

# Test keys
TEST_USER1_PRIVKEY="5c0c523f52a5b6fad39ed2403092df8cebc36318b39383bca6c00808626fab3a"  
TEST_USER1_PUBKEY="79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798"

echo "=== Simple Authentication Test ==="

# Test 1: Basic upload
echo "Test 1: Basic upload"
echo "test content" > test1.txt
file_hash=$(sha256sum test1.txt | cut -d" " -f1)

# Create auth event
event=$(nak event -k 24242 -c "" --tag "t=upload" --tag "expiration=$(date -d "+1 hour" +%s)" --tag "x=$file_hash" --sec "$TEST_USER1_PRIVKEY")
auth_header="Nostr $(echo "$event" | base64 -w 0)"

# Make upload request
response=$(curl -s -w "%{http_code}" -H "Authorization: $auth_header" -H "Content-Type: text/plain" --data-binary "@test1.txt" -X PUT "$UPLOAD_ENDPOINT" -o response1.json)

if [ "$response" = "200" ]; then
    echo "✓ Basic upload test PASSED (HTTP $response)"
else
    echo "✗ Basic upload test FAILED (HTTP $response)"
    cat response1.json
fi

# Test 2: Whitelist rule
echo
echo "Test 2: Pubkey whitelist"

# Clear rules and add whitelist
sqlite3 "$DB_PATH" "DELETE FROM auth_rules WHERE description LIKE %TEST_%;"
sqlite3 "$DB_PATH" "DELETE FROM auth_cache;"
sqlite3 "$DB_PATH" "INSERT INTO auth_rules (rule_type, rule_target, operation, priority, enabled, description) VALUES (pubkey_whitelist, , upload, 10, 1, TEST_WHITELIST);"

echo "test content 2" > test2.txt
file_hash2=$(sha256sum test2.txt | cut -d" " -f1)

event2=$(nak event -k 24242 -c "" --tag "t=upload" --tag "expiration=$(date -d "+1 hour" +%s)" --tag "x=$file_hash2" --sec "$TEST_USER1_PRIVKEY")
auth_header2="Nostr $(echo "$event2" | base64 -w 0)"

response2=$(curl -s -w "%{http_code}" -H "Authorization: $auth_header2" -H "Content-Type: text/plain" --data-binary "@test2.txt" -X PUT "$UPLOAD_ENDPOINT" -o response2.json)

if [ "$response2" = "200" ]; then
    echo "✓ Whitelist test PASSED (HTTP $response2)"
else
    echo "✗ Whitelist test FAILED (HTTP $response2)"
    cat response2.json
fi

# Cleanup
rm -f test1.txt test2.txt response1.json response2.json
sqlite3 "$DB_PATH" "DELETE FROM auth_rules WHERE description LIKE %TEST_%;"
sqlite3 "$DB_PATH" "DELETE FROM auth_cache;"

echo "=== Tests completed ==="
