#!/bin/bash
set -e

echo "⏰ Time Drift Testing Script"
echo "============================"

# Configuration
BASE_URL=${BASE_URL:-"http://localhost:8000"}
EVENT_ID=${EVENT_ID:-1}

# Check dependencies
check_dependencies() {
    echo "🔍 Checking dependencies..."
    
    if ! command -v npm >/dev/null 2>&1; then
        echo "❌ npm is required but not installed"
        exit 1
    fi
    
    if [ ! -f "playwright.config.ts" ]; then
        echo "❌ playwright.config.ts not found. Run from project root."
        exit 1
    fi
    
    echo "✅ Dependencies OK"
}

# Check server availability
check_server() {
    echo "🔍 Checking server availability at $BASE_URL..."
    
    if ! curl -s --connect-timeout 5 "$BASE_URL/api/seats/availability/$EVENT_ID" >/dev/null; then
        echo "❌ Server not accessible at $BASE_URL"
        echo ""
        echo "Start the server:"
        echo "  php artisan serve --host=0.0.0.0 --port=8000"
        exit 1
    fi
    
    echo "✅ Server is accessible"
}

# Setup test environment
setup_test_environment() {
    echo "🛠️  Setting up test environment..."
    
    # Reset server time
    echo "🕐 Resetting server time..."
    curl -s -X POST \
        -H "Content-Type: application/json" \
        -d "{\"timestamp\": \"$(date -u +%Y-%m-%dT%H:%M:%S.%3NZ)\"}" \
        "$BASE_URL/__test/time/set" >/dev/null || {
        echo "⚠️  Could not reset server time (test routes may be disabled)"
    }
    
    # Create test seats
    echo "🎫 Creating test seats..."
    curl -s -X POST \
        -H "Content-Type: application/json" \
        -d "{\"event_id\": $EVENT_ID, \"seat_count\": 20}" \
        "$BASE_URL/__test/seats/create" >/dev/null || {
        echo "⚠️  Could not create test seats (may already exist)"
    }
    
    echo "✅ Test environment ready"
}

# Run the time drift tests
run_time_drift_tests() {
    echo ""
    echo "🧪 Running time drift tests..."
    echo "=============================="
    
    # Set environment variables for tests
    export BASE_URL="$BASE_URL"
    export EVENT_ID="$EVENT_ID"
    
    # Run specific time drift test file
    npx playwright test tests/e2e/time-drift.spec.ts \
        --reporter=line \
        --project=chromium \
        2>&1 | tee time-drift-test-output.log
    
    local test_exit_code=${PIPESTATUS[0]}
    
    if [ $test_exit_code -eq 0 ]; then
        echo ""
        echo "✅ All time drift tests passed!"
    else
        echo ""
        echo "❌ Some time drift tests failed (exit code: $test_exit_code)"
        echo "Check time-drift-test-output.log for details"
    fi
    
    return $test_exit_code
}

# Analyze test results
analyze_results() {
    echo ""
    echo "📊 Time Drift Test Analysis"
    echo "==========================="
    
    if [ -f "time-drift-test-output.log" ]; then
        echo "Test Summary:"
        echo "-------------"
        
        # Extract test results
        local passed=$(grep -o "passed" time-drift-test-output.log | wc -l || echo "0")
        local failed=$(grep -o "failed" time-drift-test-output.log | wc -l || echo "0")
        local total=$((passed + failed))
        
        echo "Total tests: $total"
        echo "Passed: $passed"
        echo "Failed: $failed"
        
        if [ "$failed" -gt 0 ]; then
            echo ""
            echo "❌ Failed Tests:"
            grep -A2 -B2 "failed" time-drift-test-output.log || echo "Could not extract failed test details"
        fi
        
        echo ""
        echo "Key Test Areas:"
        echo "- ✓ Server-authoritative time behavior"
        echo "- ✓ Client time drift handling"
        echo "- ✓ Hold expiry with time skew"
        echo "- ✓ UI countdown accuracy"
        echo "- ✓ Multi-client time consistency"
    else
        echo "⚠️  No test output log found"
    fi
}

# Check system clock stability
check_system_clock() {
    echo ""
    echo "🕰️  System Clock Check"
    echo "======================"
    
    echo "Server system time: $(date)"
    
    # Check if NTP is synchronized (Linux/macOS)
    if command -v timedatectl >/dev/null 2>&1; then
        echo ""
        echo "NTP Sync Status (Linux):"
        timedatectl status | grep -E "(NTP|synchronized)" || echo "NTP status unknown"
    elif command -v sntp >/dev/null 2>&1; then
        echo ""
        echo "NTP Sync Check (macOS):"
        sntp -sS pool.ntp.org 2>&1 | head -n 1 || echo "Could not check NTP sync"
    fi
    
    echo ""
    echo "💡 Time Drift Test Best Practices:"
    echo "- Ensure server time is synchronized with NTP"
    echo "- Test with various client time drift scenarios"
    echo "- Verify server-authoritative behavior in all cases"
    echo "- Check UI displays server-based countdowns"
}

# Cleanup
cleanup() {
    echo ""
    echo "🧹 Cleaning up..."
    
    # Reset server time
    curl -s -X POST \
        -H "Content-Type: application/json" \
        -d "{\"timestamp\": \"$(date -u +%Y-%m-%dT%H:%M:%S.%3NZ)\"}" \
        "$BASE_URL/__test/time/set" >/dev/null || true
    
    echo "✅ Cleanup completed"
}

# Main execution
main() {
    local mode=${1:-"test"}
    
    case "$mode" in
        "setup")
            check_dependencies
            check_server
            setup_test_environment
            ;;
        "test")
            check_dependencies
            check_server
            setup_test_environment
            
            local test_result=0
            run_time_drift_tests || test_result=$?
            
            analyze_results
            check_system_clock
            cleanup
            
            exit $test_result
            ;;
        "analyze")
            analyze_results
            ;;
        *)
            echo "Usage: $0 [setup|test|analyze]"
            echo ""
            echo "Commands:"
            echo "  setup   - Setup test environment only"
            echo "  test    - Run full time drift tests (default)"
            echo "  analyze - Analyze existing test results"
            echo ""
            echo "Environment Variables:"
            echo "  BASE_URL  - Server URL (default: http://localhost:8000)"
            echo "  EVENT_ID  - Event ID for tests (default: 1)"
            exit 1
            ;;
    esac
}

# Handle cleanup on script exit
trap cleanup EXIT

# Run main function
main "$@"
