#!/usr/bin/env bash
# Test Setup Script for Phase 9 Integration Tests
# This script ensures SurrealDB has the correct schema before running tests

set -e

echo "🔧 Setting up test environment for Phase 9..."

# Check if SurrealDB is running
if ! nc -z 127.0.0.1 8000 2>/dev/null; then
    echo "❌ SurrealDB is not running on port 8000"
    echo "   Start it with: docker run -p 8000:8000 surrealdb/surrealdb:latest start --bind 0.0.0.0:8000 --user root --pass root"
    exit 1
fi

echo "✓ SurrealDB is running"

# Apply migrations using surreal CLI if available, otherwise use curl
if command -v surreal &> /dev/null; then
    echo "✓ Found surreal CLI"

    # Apply RLM schema migration
    echo "📋 Applying RLM schema migration..."
    surreal sql --endpoint http://127.0.0.1:8000 --namespace test_rlm_e2e --database test_rlm_e2e --username root --password root < ../../../migrations/008_rlm_schema.surql

    echo "✓ Schema migration applied"
else
    echo "⚠ surreal CLI not found, using curl..."

    # Read migration file and apply via HTTP
    MIGRATION=$(cat ../../../migrations/008_rlm_schema.surql)

    curl -X POST http://127.0.0.1:8000/sql \
        -H "Accept: application/json" \
        -H "NS: test_rlm_e2e" \
        -H "DB: test_rlm_e2e" \
        -u "root:root" \
        -d "$MIGRATION" > /dev/null 2>&1

    echo "✓ Schema applied via curl"
fi

echo ""
echo "✅ Test environment ready!"
echo ""
echo "Run tests with:"
echo "  cargo test -p vapora-rlm --test e2e_integration -- --ignored --test-threads=1"
echo "  cargo test -p vapora-rlm --test performance_test -- --ignored"
echo "  cargo test -p vapora-rlm --test security_test -- --ignored"
