#!/bin/bash

# Simple authentication test
set -e

SERVER_URL="http://localhost:9001"
UPLOAD_ENDPOINT="${SERVER_URL}/upload"
TEST_USER1_PRIVKEY="5c0c523f52a5b6fad39ed2403092df8cebc36318b39383bca6c00808626fab3a"

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

# Create a small test file
echo "Test file content $(date)" > /tmp/simple_test.txt
FILE_HASH=$(sha256sum /tmp/simple_test.txt | cut -d' ' -f1)

echo "Test file hash: $FILE_HASH"

# Create auth event
EVENT=$(nak event -k 24242 -c "" \
    --tag "t=upload" \
    --tag "x=${FILE_HASH}" \
    --tag "expiration=$(date -d '+1 hour' +%s)" \
    --sec "$TEST_USER1_PRIVKEY")

echo "Generated event: $EVENT"

# Create auth header
AUTH_HEADER="Nostr $(echo "$EVENT" | base64 -w 0)"

echo "Auth header length: ${#AUTH_HEADER}"

# Test upload
echo "Testing upload..."
HTTP_STATUS=$(curl -s -w "%{http_code}" \
    -H "Authorization: $AUTH_HEADER" \
    -H "Content-Type: text/plain" \
    --data-binary "@/tmp/simple_test.txt" \
    -X PUT "$UPLOAD_ENDPOINT" \
    -o /tmp/upload_response.txt)

echo "HTTP Status: $HTTP_STATUS"
echo "Response:"
cat /tmp/upload_response.txt
echo

# Cleanup
rm -f /tmp/simple_test.txt /tmp/upload_response.txt

echo "Test completed with status: $HTTP_STATUS"