#!/bin/bash

# E2E Test Runner
# Runs all end-to-end tests in sequence

set -e

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
BASE_URL="http://localhost:9876"

echo "=== E2E Test Suite Runner ==="
echo "Testing gateway at: $BASE_URL"
echo ""

# 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: ./bin/gateway -config configs/config.yaml"
    exit 1
fi
echo "✅ Gateway is running"
echo ""

# Test results tracking
TOTAL_TESTS=0
PASSED_TESTS=0
FAILED_TESTS=0

# Function to run a test and track results
run_test() {
    local test_script="$1"
    local test_name="$(basename "$test_script" .sh)"
    
    echo "🧪 Running test: $test_name"
    echo "----------------------------------------"
    
    TOTAL_TESTS=$((TOTAL_TESTS + 1))
    
    if bash "$test_script"; then
        PASSED_TESTS=$((PASSED_TESTS + 1))
        echo "✅ $test_name PASSED"
    else
        FAILED_TESTS=$((FAILED_TESTS + 1))
        echo "❌ $test_name FAILED"
    fi
    
    echo ""
}

# Run all tests
run_test "$SCRIPT_DIR/auth_flow_test.sh"
run_test "$SCRIPT_DIR/upload_small_file_test.sh"
run_test "$SCRIPT_DIR/upload_large_file_test.sh"
run_test "$SCRIPT_DIR/admin_operations_test.sh"

# Final results
echo "=========================================="
echo "E2E Test Suite Results"
echo "=========================================="
echo "Total tests:  $TOTAL_TESTS"
echo "Passed:       $PASSED_TESTS"
echo "Failed:       $FAILED_TESTS"
echo "Success rate: $(echo "scale=1; $PASSED_TESTS * 100 / $TOTAL_TESTS" | bc -l)%"
echo ""

if [ $FAILED_TESTS -eq 0 ]; then
    echo "🎉 All E2E tests passed!"
    echo "✅ Gateway ready for deployment"
    exit 0
else
    echo "❌ Some E2E tests failed"
    echo "🔧 Please fix failing tests before deployment"
    exit 1
fi