#!/bin/bash

# E2E Test Setup: Create Test Authentication Session
# Creates a test user and session in the database for E2E testing

set -e

BASE_URL="http://localhost:9876"
TEST_PUBKEY="1234567890abcdef1234567890abcdef1234567890abcdef1234567890abcdef"
SESSION_TOKEN="test_session_token_${TEST_PUBKEY}"
DB_PATH="data/metadata.db"

echo "=== Setting up test authentication for E2E tests ==="

# Check if gateway is running
echo "Checking if gateway is running..."
if ! curl -s "$BASE_URL/api/health" > /dev/null; then
    echo "❌ Gateway is not running at $BASE_URL"
    echo "Please start the gateway first: ./gateway -config configs/config.yaml"
    exit 1
fi
echo "✅ Gateway is running"

# Check if database exists
if [ ! -f "$DB_PATH" ]; then
    echo "❌ Database not found at $DB_PATH"
    echo "Please ensure the gateway has been started and database is initialized"
    exit 1
fi

echo "Setting up test user and session..."

# Create test user in database
sqlite3 "$DB_PATH" << EOF
INSERT OR IGNORE INTO users (pubkey, storage_used, file_count, last_login, created_at)
VALUES ('$TEST_PUBKEY', 0, 0, datetime('now'), datetime('now'));

INSERT OR REPLACE INTO sessions (token, pubkey, created_at, expires_at)
VALUES ('$SESSION_TOKEN', '$TEST_PUBKEY', datetime('now'), datetime('now', '+24 hours'));
EOF

if [ $? -eq 0 ]; then
    echo "✅ Test user and session created successfully"
    echo "   Test Pubkey: $TEST_PUBKEY"
    echo "   Session Token: $SESSION_TOKEN"
    echo ""
    echo "🧪 Ready for E2E upload tests!"
    echo ""
    echo "You can now run:"
    echo "   ./test/e2e/upload_small_file_test.sh"
    echo "   ./test/e2e/upload_large_file_test.sh"
else
    echo "❌ Failed to create test session"
    exit 1
fi