#!/bin/bash

# Global Gala API Integration Test Runner
# ======================================

set -e

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

# Configuration
TEST_ENV=".env.testing"
PHPUNIT_CONFIG="phpunit-api.xml"
COVERAGE_DIR="tests/coverage"

# Functions
print_header() {
    echo -e "${BLUE}========================================${NC}"
    echo -e "${BLUE}  Global Gala API Integration Tests${NC}"
    echo -e "${BLUE}========================================${NC}"
}

print_section() {
    echo -e "\n${YELLOW}▸ $1${NC}"
}

print_success() {
    echo -e "${GREEN}✓ $1${NC}"
}

print_error() {
    echo -e "${RED}✗ $1${NC}"
}

# Check prerequisites
check_prerequisites() {
    print_section "Checking prerequisites"
    
    # Check if PHP is installed
    if ! command -v php &> /dev/null; then
        print_error "PHP is not installed"
        exit 1
    fi
    print_success "PHP found: $(php -v | head -n1)"
    
    # Check if Composer is installed
    if ! command -v composer &> /dev/null; then
        print_error "Composer is not installed"
        exit 1
    fi
    print_success "Composer found: $(composer --version)"
    
    # Check if testing environment file exists
    if [ ! -f "$TEST_ENV" ]; then
        print_error "Testing environment file not found: $TEST_ENV"
        echo "Creating default testing environment..."
        cp .env.example "$TEST_ENV"
        print_success "Created $TEST_ENV from .env.example"
    else
        print_success "Testing environment file found"
    fi
    
    # Check if vendor directory exists
    if [ ! -d "vendor" ]; then
        print_error "Dependencies not installed"
        echo "Installing dependencies..."
        composer install --no-interaction
        print_success "Dependencies installed"
    else
        print_success "Dependencies found"
    fi
}

# Prepare test database
prepare_database() {
    print_section "Preparing test database"
    
    # Create SQLite test database if it doesn't exist
    if [ ! -f "database/testing.sqlite" ]; then
        touch database/testing.sqlite
        print_success "Created SQLite test database"
    else
        print_success "Test database exists"
    fi
    
    # Run migrations
    php artisan migrate:fresh --env=testing --force
    print_success "Database migrations completed"
    
    # Seed test data if needed
    # php artisan db:seed --env=testing --class=TestSeeder --force
}

# Clear caches
clear_caches() {
    print_section "Clearing caches"
    
    php artisan cache:clear --env=testing
    php artisan config:clear --env=testing
    php artisan route:clear --env=testing
    php artisan view:clear --env=testing
    
    print_success "Caches cleared"
}

# Run specific test suite
run_test_suite() {
    local suite=$1
    local description=$2
    
    echo -e "\n${BLUE}Running: $description${NC}"
    
    if vendor/bin/phpunit --configuration="$PHPUNIT_CONFIG" --testsuite="$suite" --colors=always; then
        print_success "$description passed"
        return 0
    else
        print_error "$description failed"
        return 1
    fi
}

# Run all tests
run_all_tests() {
    print_section "Running all API integration tests"
    
    # Track failures
    local failed_suites=()
    
    # Run individual test suites
    run_test_suite "Authentication" "Authentication API Tests" || failed_suites+=("Authentication")
    run_test_suite "Booking" "Seat Booking API Tests" || failed_suites+=("Booking")
    run_test_suite "Orders" "Order Management API Tests" || failed_suites+=("Orders")
    run_test_suite "Venues" "Venue Management API Tests" || failed_suites+=("Venues")
    run_test_suite "QRCodes" "QR Code API Tests" || failed_suites+=("QRCodes")
    run_test_suite "Analytics" "Analytics API Tests" || failed_suites+=("Analytics")
    run_test_suite "Admin" "Admin API Tests" || failed_suites+=("Admin")
    run_test_suite "TicketPDF" "Ticket PDF API Tests" || failed_suites+=("TicketPDF")
    run_test_suite "RateLimiting" "Rate Limiting Tests" || failed_suites+=("RateLimiting")
    
    # Summary
    echo -e "\n${BLUE}========================================${NC}"
    echo -e "${BLUE}  Test Summary${NC}"
    echo -e "${BLUE}========================================${NC}"
    
    if [ ${#failed_suites[@]} -eq 0 ]; then
        print_success "All test suites passed!"
        return 0
    else
        print_error "Failed test suites: ${failed_suites[*]}"
        return 1
    fi
}

# Run tests with coverage
run_with_coverage() {
    print_section "Running tests with code coverage"
    
    # Create coverage directory if it doesn't exist
    mkdir -p "$COVERAGE_DIR"
    
    # Run PHPUnit with coverage
    vendor/bin/phpunit \
        --configuration="$PHPUNIT_CONFIG" \
        --coverage-html="$COVERAGE_DIR/html" \
        --coverage-text="$COVERAGE_DIR/coverage.txt" \
        --coverage-clover="$COVERAGE_DIR/clover.xml" \
        --colors=always
    
    print_success "Coverage report generated in $COVERAGE_DIR"
    
    # Display coverage summary
    if [ -f "$COVERAGE_DIR/coverage.txt" ]; then
        echo -e "\n${YELLOW}Coverage Summary:${NC}"
        tail -n 20 "$COVERAGE_DIR/coverage.txt"
    fi
}

# Run specific test file
run_specific_test() {
    local test_file=$1
    
    print_section "Running specific test: $test_file"
    
    vendor/bin/phpunit \
        --configuration="$PHPUNIT_CONFIG" \
        "$test_file" \
        --colors=always
}

# Main execution
main() {
    print_header
    
    # Parse command line arguments
    case "${1:-all}" in
        all)
            check_prerequisites
            prepare_database
            clear_caches
            run_all_tests
            ;;
        coverage)
            check_prerequisites
            prepare_database
            clear_caches
            run_with_coverage
            ;;
        auth|authentication)
            check_prerequisites
            prepare_database
            clear_caches
            run_test_suite "Authentication" "Authentication API Tests"
            ;;
        booking)
            check_prerequisites
            prepare_database
            clear_caches
            run_test_suite "Booking" "Seat Booking API Tests"
            ;;
        orders)
            check_prerequisites
            prepare_database
            clear_caches
            run_test_suite "Orders" "Order Management API Tests"
            ;;
        venues)
            check_prerequisites
            prepare_database
            clear_caches
            run_test_suite "Venues" "Venue Management API Tests"
            ;;
        qr|qrcode)
            check_prerequisites
            prepare_database
            clear_caches
            run_test_suite "QRCodes" "QR Code API Tests"
            ;;
        analytics)
            check_prerequisites
            prepare_database
            clear_caches
            run_test_suite "Analytics" "Analytics API Tests"
            ;;
        admin)
            check_prerequisites
            prepare_database
            clear_caches
            run_test_suite "Admin" "Admin API Tests"
            ;;
        pdf|ticket)
            check_prerequisites
            prepare_database
            clear_caches
            run_test_suite "TicketPDF" "Ticket PDF API Tests"
            ;;
        rate|ratelimit)
            check_prerequisites
            prepare_database
            clear_caches
            run_test_suite "RateLimiting" "Rate Limiting Tests"
            ;;
        file)
            if [ -z "$2" ]; then
                print_error "Please specify a test file"
                echo "Usage: $0 file path/to/TestFile.php"
                exit 1
            fi
            check_prerequisites
            prepare_database
            clear_caches
            run_specific_test "$2"
            ;;
        help|--help|-h)
            echo "Global Gala API Integration Test Runner"
            echo ""
            echo "Usage: $0 [command] [options]"
            echo ""
            echo "Commands:"
            echo "  all              Run all API integration tests (default)"
            echo "  coverage         Run tests with code coverage report"
            echo "  auth             Run authentication tests only"
            echo "  booking          Run booking/seat reservation tests only"
            echo "  orders           Run order management tests only"
            echo "  venues           Run venue management tests only"
            echo "  qr               Run QR code tests only"
            echo "  analytics        Run analytics tests only"
            echo "  admin            Run admin tests only"
            echo "  pdf              Run ticket PDF tests only"
            echo "  rate             Run rate limiting tests only"
            echo "  file <path>      Run a specific test file"
            echo "  help             Show this help message"
            echo ""
            echo "Examples:"
            echo "  $0                    # Run all tests"
            echo "  $0 coverage           # Run with coverage"
            echo "  $0 auth               # Run auth tests only"
            echo "  $0 file tests/Feature/API/AuthenticationApiTest.php"
            ;;
        *)
            print_error "Unknown command: $1"
            echo "Use '$0 help' for usage information"
            exit 1
            ;;
    esac
}

# Run main function
main "$@"