#!/bin/bash

# E2E Test: Small File Upload Flow
# Tests blob storage path for files under 100MB

set -e

BASE_URL="http://localhost:9876"
TEST_FILE="/tmp/small_test_file.txt"
GATEWAY_LOG="/tmp/gateway_test.log"

echo "=== Small File Upload E2E Test ==="

# Create test file (1MB)
echo "Creating 1MB test file..."
dd if=/dev/urandom of="$TEST_FILE" bs=1024 count=1024 2>/dev/null
echo "Created test file: $(ls -lh $TEST_FILE)"

# Test 1: Health check
echo "Testing health endpoint..."
HEALTH_RESPONSE=$(curl -s "$BASE_URL/api/health")
echo "Health response: $HEALTH_RESPONSE"

if ! echo "$HEALTH_RESPONSE" | grep -q '"status":"ok"'; then
    echo "❌ Health check failed"
    exit 1
fi
echo "✅ Health check passed"

# Test 2: Upload file (requires authentication)
echo "Uploading small file..."
# Note: This test requires a running gateway with a test session in the database
# For full E2E testing, use the test setup that creates proper authentication
TEST_PUBKEY="1234567890abcdef1234567890abcdef1234567890abcdef1234567890abcdef"
SESSION_TOKEN="test_session_token_${TEST_PUBKEY}"

UPLOAD_RESPONSE=$(curl -s -X POST \
    -H "Authorization: Bearer $SESSION_TOKEN" \
    -F "file=@$TEST_FILE" \
    "$BASE_URL/api/upload")

echo "Upload response: $UPLOAD_RESPONSE"

# Extract file hash from response
FILE_HASH=$(echo "$UPLOAD_RESPONSE" | grep -o '"file_hash":"[^"]*"' | cut -d'"' -f4)
MESSAGE=$(echo "$UPLOAD_RESPONSE" | grep -o '"message":"[^"]*"' | cut -d'"' -f4)

if [ -z "$FILE_HASH" ]; then
    echo "❌ Failed to get file hash from upload response"
    exit 1
fi

echo "✅ File uploaded successfully"
echo "   File hash: $FILE_HASH"
echo "   Message: $MESSAGE"

# Verify storage type is blob for small file (check message)
if ! echo "$MESSAGE" | grep -q "as blob"; then
    echo "❌ Expected 'as blob' in message but got '$MESSAGE'"
    exit 1
fi
echo "✅ Correct storage type (blob) for small file"

# Test 3: Download file
echo "Downloading file..."
DOWNLOAD_FILE="/tmp/downloaded_small_file.txt"
curl -s -H "User-Agent: TestRunner/1.0" "$BASE_URL/api/download/$FILE_HASH" -o "$DOWNLOAD_FILE"

if [ ! -f "$DOWNLOAD_FILE" ]; then
    echo "❌ Download failed - file not created"
    exit 1
fi

# Verify file integrity
ORIGINAL_HASH=$(sha256sum "$TEST_FILE" | cut -d' ' -f1)
DOWNLOADED_HASH=$(sha256sum "$DOWNLOAD_FILE" | cut -d' ' -f1)

if [ "$ORIGINAL_HASH" != "$DOWNLOADED_HASH" ]; then
    echo "❌ File integrity check failed"
    echo "   Original:   $ORIGINAL_HASH"
    echo "   Downloaded: $DOWNLOADED_HASH"
    exit 1
fi
echo "✅ File downloaded successfully with correct content"

# Test 4: Get file info
echo "Getting file info..."
INFO_RESPONSE=$(curl -s "$BASE_URL/api/info/$FILE_HASH")
echo "Info response: $INFO_RESPONSE"

if ! echo "$INFO_RESPONSE" | grep -q '"success":true'; then
    echo "❌ File info request failed"
    exit 1
fi
echo "✅ File info retrieved successfully"

# Test 5: System stats
echo "Checking system stats..."
STATS_RESPONSE=$(curl -s "$BASE_URL/api/stats")
echo "Stats response: $STATS_RESPONSE"

# Verify blob count increased
BLOB_COUNT=$(echo "$STATS_RESPONSE" | grep -o '"blobs":[0-9]*' | cut -d':' -f2)
if [ "$BLOB_COUNT" != "1" ]; then
    echo "❌ Expected 1 blob in stats but got $BLOB_COUNT"
    exit 1
fi
echo "✅ System stats updated correctly"

# Cleanup
rm -f "$TEST_FILE" "$DOWNLOAD_FILE"

echo ""
echo "🎉 All small file upload tests passed!"
echo "✅ Upload -> Blob Storage -> Download cycle working"
echo "✅ File integrity preserved"
echo "✅ System stats tracking correctly"