#!/bin/bash

# E2E Test Setup Script - Comprehensive High-Impact Version
# This script sets up the complete E2E testing environment with all safeguards

set -euo pipefail  # Exit on any error, unset variable, or pipe failure

echo "🎯 Setting up Comprehensive E2E Test Environment..."

# Colors for output
RED='\033[0;31m'
GREEN='\033[0;32m' 
YELLOW='\033[1;33m'
NC='\033[0m' # No Color

# Error handling
error_exit() {
    echo -e "${RED}❌ Error: $1${NC}" >&2
    exit 1
}

success() {
    echo -e "${GREEN}✅ $1${NC}"
}

warning() {
    echo -e "${YELLOW}⚠️  $1${NC}"
}

# Check prerequisites
check_prerequisites() {
    echo "🔍 Checking prerequisites..."
    
    # Check Node.js version
    if ! command -v node &> /dev/null; then
        error_exit "Node.js is not installed"
    fi
    
    NODE_VERSION=$(node --version | cut -d'v' -f2)
    if [[ "$(printf '%s\n' "18.0.0" "$NODE_VERSION" | sort -V | head -n1)" != "18.0.0" ]]; then
        error_exit "Node.js 18+ required, found $NODE_VERSION"
    fi
    
    # Check PHP version
    if ! command -v php &> /dev/null; then
        error_exit "PHP is not installed"
    fi
    
    PHP_VERSION=$(php --version | head -n1 | cut -d' ' -f2 | cut -d'.' -f1,2)
    if [[ "$(printf '%s\n' "8.1" "$PHP_VERSION" | sort -V | head -n1)" != "8.1" ]]; then
        error_exit "PHP 8.1+ required, found $PHP_VERSION"
    fi
    
    success "Prerequisites check passed"
}

# Install dependencies
install_dependencies() {
    echo "📦 Installing dependencies..."
    
    # Install Node.js dependencies
    if [ -f package-lock.json ]; then
        npm ci || error_exit "Failed to install Node.js dependencies"
    else
        npm install || error_exit "Failed to install Node.js dependencies"
    fi
    
    # Install PHP dependencies
    if command -v composer &> /dev/null; then
        composer install --no-interaction --prefer-dist --optimize-autoloader || error_exit "Failed to install PHP dependencies"
    else
        warning "Composer not found, skipping PHP dependency installation"
    fi
    
    success "Dependencies installed"
}

# Install Playwright browsers
install_playwright() {
    echo "🎭 Installing Playwright browsers..."
    
    npx playwright install --with-deps || error_exit "Failed to install Playwright browsers"
    
    success "Playwright browsers installed"
}

# Setup test database
setup_database() {
    echo "🗄️  Setting up test database..."
    
    # Copy test environment config
    if [ ! -f .env.testing ]; then
        error_exit ".env.testing file not found"
    fi
    
    cp .env.testing .env
    
    # Generate application key if needed
    if ! grep -q "APP_KEY=base64:" .env; then
        php artisan key:generate --force || error_exit "Failed to generate app key"
    fi
    
    # Create SQLite database for fast tests
    touch database/database.sqlite || error_exit "Failed to create SQLite database"
    
    # Run migrations
    php artisan migrate --force --env=testing || error_exit "Failed to run database migrations"
    
    success "Test database setup completed"
}

# Build assets
build_assets() {
    echo "🏗️  Building assets for testing..."
    
    export NODE_OPTIONS="--openssl-legacy-provider"
    npm run production || error_exit "Failed to build assets"
    
    success "Assets built successfully"
}

# Start test server
start_server() {
    echo "🚀 Starting test server..."
    
    # Check if server is already running
    if curl -f http://127.0.0.1:8080 &>/dev/null; then
        warning "Server already running on port 8080"
        return 0
    fi
    
    # Start PHP development server in background
    APP_ENV=testing php -S 127.0.0.1:8080 -t public &
    SERVER_PID=$!
    
    # Wait for server to be ready
    echo "Waiting for server to start..."
    for i in {1..30}; do
        if curl -f http://127.0.0.1:8080 &>/dev/null; then
            success "Test server started (PID: $SERVER_PID)"
            return 0
        fi
        sleep 1
    done
    
    error_exit "Server failed to start within 30 seconds"
}

# Run comprehensive test setup
run_test_setup() {
    echo "🧪 Running comprehensive test setup..."
    
    # Reset database state
    curl -s -X POST http://127.0.0.1:8080/__test/database/reset || warning "Could not reset test database"
    
    # Reset time provider
    curl -s -X POST "http://127.0.0.1:8080/__test/time/travel?seconds=0" || warning "Could not reset time provider"
    
    # Create test seats
    curl -s -X POST http://127.0.0.1:8080/__test/seats/create \
        -H "Content-Type: application/json" \
        -d '{"event_id":123,"rows":5,"seats_per_row":10}' || warning "Could not create test seats"
    
    success "Test environment setup completed"
}

# Validate E2E environment
validate_environment() {
    echo "🔬 Validating E2E environment..."
    
    # Test basic API endpoints
    if ! curl -f http://127.0.0.1:8080/api/seats/availability/123 &>/dev/null; then
        error_exit "Seat availability API endpoint not accessible"
    fi
    
    # Test time travel endpoint
    RESPONSE=$(curl -s -X POST "http://127.0.0.1:8080/__test/time/travel?seconds=1")
    if ! echo "$RESPONSE" | grep -q "time_traveled"; then
        error_exit "Time travel endpoint not working"
    fi
    
    success "Environment validation passed"
}

# Main execution
main() {
    echo "🎯 E2E Test Environment Setup - High-Impact Edition"
    echo "=================================================="
    
    check_prerequisites
    install_dependencies
    install_playwright
    setup_database
    build_assets
    start_server
    run_test_setup
    validate_environment
    
    echo ""
    echo -e "${GREEN}🎉 E2E Test Environment Ready!${NC}"
    echo ""
    echo "Available test commands:"
    echo "  npm run test:e2e                    # Run all E2E tests"
    echo "  npm run test:e2e:ui                 # Run with Playwright UI"
    echo "  npm run test:e2e:comprehensive      # Run comprehensive test suite"
    echo "  npm run test:e2e:debug              # Run with debugging"
    echo ""
    echo "Test Coverage:"
    echo "  ✅ Happy paths (single & multi-seat booking)"
    echo "  ⚡ Race conditions (concurrent access, expiry)"
    echo "  🔒 Data integrity (idempotency, price snapshots)"
    echo "  🎨 UI accessibility (ARIA labels, keyboard nav)"
    echo "  🧪 Edge cases (invalid inputs, spam clicks)"
    echo ""
    echo "High-Impact Features Enabled:"
    echo "  ⏰ Deterministic time travel (no cron flakiness)"
    echo "  🔐 Database row locking & constraints"
    echo "  🛡️  Idempotency protection"
    echo "  📸 Price snapshot integrity"
    echo "  ♿ Accessibility compliance"
    echo "  🚫 Spam prevention"
    echo ""
    echo "Server: http://127.0.0.1:8080"
    echo "Test Environment: Ready for bulletproof booking validation"
}

# Handle script termination
cleanup() {
    if [[ -n "${SERVER_PID:-}" ]]; then
        warning "Cleaning up server process ($SERVER_PID)"
        kill $SERVER_PID 2>/dev/null || true
    fi
}

trap cleanup EXIT

# Run main function
main "$@"
