#!/bin/bash
# Run complete navigation test suite
#
# Usage: ./full-test-suite.sh

set -e

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

echo "🧭 Running complete navigation test suite..."
echo "🌐 Base URL: $BASE_URL"
echo ""

# Check if server is running
if ! curl -f -s "$BASE_URL/health" > /dev/null 2>&1; then
    echo "❌ Server not running at $BASE_URL"
    echo "💡 Start server with: just dev::with-nav-test"
    exit 1
fi

# Test counter
tests_passed=0
tests_failed=0
total_tests=0

# Function to run test and track results
run_test() {
    local test_name="$1"
    local test_command="$2"

    echo "🧪 Running: $test_name"
    total_tests=$((total_tests + 1))

    if eval "$test_command"; then
        tests_passed=$((tests_passed + 1))
        echo "✅ PASSED: $test_name"
    else
        tests_failed=$((tests_failed + 1))
        echo "❌ FAILED: $test_name"
    fi
    echo ""
}

# 1. Validate all routes first
run_test "Route Validation" "$SCRIPT_DIR/validate-all-routes.sh"

# 2. Test individual route resolution
echo "📋 Testing individual routes..."
run_test "Home Route (/)" "$SCRIPT_DIR/test-single-route.sh /"
run_test "Services Route (/services)" "$SCRIPT_DIR/test-single-route.sh /services"

# Check if Spanish routes exist
if curl -s "$BASE_URL/api/nav-test/resolve?path=/es" | grep -q '"valid":true'; then
    run_test "Spanish Home (/es)" "$SCRIPT_DIR/test-single-route.sh /es"
    run_test "Spanish Contact (/es/contactar)" "$SCRIPT_DIR/test-single-route.sh /es/contactar"
fi

# 3. Test navigation sequences
echo "📋 Testing navigation sequences..."
run_test "Home to Services" "$SCRIPT_DIR/test-navigation-sequence.sh / /services"
run_test "Services to Contact" "$SCRIPT_DIR/test-navigation-sequence.sh /services /contact"

# Test cross-language navigation if Spanish routes exist
if curl -s "$BASE_URL/api/nav-test/resolve?path=/es" | grep -q '"valid":true'; then
    run_test "English to Spanish" "$SCRIPT_DIR/test-navigation-sequence.sh / /es"
fi

# 4. Performance benchmarks
echo "📋 Running performance benchmarks..."
run_test "Home Route Benchmark" "$SCRIPT_DIR/benchmark-route.sh / 100"

if curl -s "$BASE_URL/api/nav-test/resolve?path=/services" | grep -q '"valid":true'; then
    run_test "Services Route Benchmark" "$SCRIPT_DIR/benchmark-route.sh /services 100"
fi

# 5. Final summary
echo "================================"
echo "🧭 Navigation Test Suite Results"
echo "================================"
echo "Total Tests: $total_tests"
echo "Passed: $tests_passed"
echo "Failed: $tests_failed"

if [ $tests_failed -eq 0 ]; then
    echo "🎉 All tests passed!"
    exit 0
else
    echo "❌ $tests_failed tests failed"
    echo ""
    echo "💡 Check individual test output above for details"
    echo "💡 Verify your route configuration in site/config/routes/"
    exit 1
fi
