#!/bin/bash

# Test runner with automatic database cleanup
set -e

echo "🚀 Running tests with automatic cleanup..."

# Store the script directory
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
PROJECT_ROOT="$(cd "$SCRIPT_DIR/.." && pwd)"

# Source environment
source "$PROJECT_ROOT/.env"

# Function to cleanup on exit (success or failure)
cleanup_on_exit() {
    local exit_code=$?
    echo ""
    if [ $exit_code -eq 0 ]; then
        echo "✅ Tests completed successfully"
    else
        echo "❌ Tests failed with exit code $exit_code"
    fi
    
    echo "🧹 Cleaning up test database..."
    
    if [ -n "$TEST_DATABASE_URL" ]; then
        # Clean up main memories table
        psql "$TEST_DATABASE_URL" -c "TRUNCATE TABLE memories CASCADE;" 2>/dev/null || true
        
        # Clean up any test schemas
        psql "$TEST_DATABASE_URL" -t -c "SELECT schemaname FROM pg_tables WHERE schemaname LIKE 'test_schema_%' GROUP BY schemaname;" 2>/dev/null | while read schema; do
            if [ -n "$schema" ]; then
                schema=$(echo "$schema" | xargs)  # Trim whitespace
                echo "  Dropping test schema: $schema"
                psql "$TEST_DATABASE_URL" -c "DROP SCHEMA IF EXISTS $schema CASCADE;" 2>/dev/null || true
            fi
        done
        
        # Verify cleanup
        local count
        count=$(psql "$TEST_DATABASE_URL" -t -c "SELECT COUNT(*) FROM memories;" 2>/dev/null | xargs)
        echo "  Test database cleaned up (${count:-0} memories remaining)"
    else
        echo "  Warning: TEST_DATABASE_URL not set, skipping cleanup"
    fi
    
    exit $exit_code
}

# Set trap to cleanup on exit
trap cleanup_on_exit EXIT

# Change to project directory
cd "$PROJECT_ROOT"

echo "📊 Pre-test database state:"
if [ -n "$TEST_DATABASE_URL" ]; then
    psql "$TEST_DATABASE_URL" -c "SELECT COUNT(*) as memory_count FROM memories;" 2>/dev/null || echo "  Could not check database state"
fi

echo ""
echo "🧪 Running tests..."

# Export TEST_DATABASE_URL so cargo test can see it
export TEST_DATABASE_URL
export DATABASE_URL

# Run tests based on arguments
if [ $# -eq 0 ]; then
    # No arguments - run all tests sequentially to avoid conflicts
    echo "Running all tests (sequential to prevent database conflicts)..."
    cargo test -- --test-threads=1
else
    # Arguments provided - run specific tests
    echo "Running specific tests: $*"
    cargo test "$@"
fi

echo ""
echo "📊 Post-test database state (before cleanup):"
if [ -n "$TEST_DATABASE_URL" ]; then
    psql "$TEST_DATABASE_URL" -c "SELECT COUNT(*) as memory_count FROM memories;" 2>/dev/null || echo "  Could not check database state"
fi

# Cleanup will happen automatically via trap