#!/bin/bash

# E2E Test Setup Script
# Prepares the environment for seat booking end-to-end tests

set -e

echo "🎯 Setting up E2E test environment..."

# Check if we're in the right directory
if [ ! -f "artisan" ]; then
    echo "❌ Error: Please run this script from the Laravel project root"
    exit 1
fi

# Check if .env.testing exists
if [ ! -f ".env.testing" ]; then
    echo "📝 Creating .env.testing file..."
    cp .env.example .env.testing
    
    # Update for testing
    sed -i '' 's/APP_ENV=local/APP_ENV=testing/' .env.testing
    sed -i '' 's/DB_DATABASE=Events54in2022/DB_DATABASE=showprima_test/' .env.testing
    sed -i '' 's/QUEUE_CONNECTION=sync/QUEUE_CONNECTION=sync/' .env.testing
    
    echo "✅ .env.testing created and configured"
fi

# Install PHP dependencies if needed
if [ ! -d "vendor" ]; then
    echo "📦 Installing PHP dependencies..."
    composer install
fi

# Install npm dependencies if needed  
if [ ! -d "node_modules" ]; then
    echo "📦 Installing npm dependencies..."
    npm install
fi

# Install Playwright browsers
echo "🎭 Installing Playwright browsers..."
npx playwright install --with-deps chromium firefox

# Check if database exists and create if needed
echo "🗄️  Setting up test database..."
php artisan migrate --env=testing --force || true

# Seed test data
echo "🌱 Seeding test data..."
php artisan db:seed --class=E2ETestSeeder --env=testing

# Build assets
echo "🏗️  Building assets..."
npm run prod

echo ""
echo "✅ E2E test environment setup complete!"
echo ""
echo "🚀 To run tests:"
echo "   npm run test:e2e           # Run all tests"
echo "   npm run test:e2e:ui        # Run with UI"
echo "   npm run test:e2e:debug     # Debug mode"
echo ""
echo "🔧 To start local server:"
echo "   php -S 127.0.0.1:8080 -t public"
echo ""
