#!/bin/bash

# Simple test to verify authentication works with hashed tokens

set -euo pipefail

SERVER_PID=""

# Cleanup function
function cleanup() {
    if [ -n "$SERVER_PID" ]; then
        echo ""
        echo "Cleaning up: Stopping server (PID: $SERVER_PID)..."
        kill $SERVER_PID 2>/dev/null || true
        wait $SERVER_PID 2>/dev/null || true
    fi
}

# Set up trap to ensure cleanup on exit
trap cleanup EXIT INT TERM

echo "Simple authentication test with bcrypt hashes"

TEST_TOKEN="test123"
HASH=$(../output/hash_token -c 10 -q "${TEST_TOKEN}")
echo "Generated hash for '${TEST_TOKEN}': ${HASH:0:20}..."

# Create config with hashed token
cat > ~/.config/simple_object_storage/sos_config.json << EOF
{
    "write_tokens": ["$HASH"],
    "rate_limiting": {
        "auth_rate_limit": 5,
        "auth_window_seconds": 2
    },
    "port": 7703,
    "host": "127.0.0.1"
}
EOF

# Make sure no server is running
fuser -k 7703/tcp 2>/dev/null || true
sleep 1

# Start server with hashed config
echo "Starting server with hashed token..."
../output/simple-object-server &
SERVER_PID=$!
sleep 2

# Test with plaintext token (server has hash)
echo "Testing with plaintext token against hashed config..."
RESPONSE=$(curl -s -X PUT \
    -H "Authorization: Bearer ${TEST_TOKEN}" \
    -F "file=@test.sh" \
    -F 'metadata={"labeltags":["test:hashed"]}' \
    "http://127.0.0.1:7703/upload")

if echo "$RESPONSE" | grep -q '"result":"success"'; then
    echo "✓ Authentication successful"
    HASH_RETURNED=$(echo "$RESPONSE" | jq -r '.hash')
    # Clean up
    curl -s -H "Authorization: Bearer ${TEST_TOKEN}" \
        "http://127.0.0.1:7703/deleteobject?hash=${HASH_RETURNED}" > /dev/null
else
    echo "✗ Authentication failed: $RESPONSE"
fi

# Test with wrong token
echo "Testing with wrong token (should fail)..."
RESPONSE=$(curl -s -X PUT \
    -H "Authorization: Bearer wrongtoken" \
    -F "file=@test.sh" \
    -F 'metadata={"labeltags":["test:wrong"]}' \
    "http://127.0.0.1:7703/upload")

if echo "$RESPONSE" | grep -q '"error"'; then
    echo "✓ Invalid token correctly rejected"
else
    echo "✗ Invalid token was incorrectly accepted: $RESPONSE"
fi

echo ""
echo "Test complete!"
# Cleanup will be handled by the trap