#!/bin/bash

# Payment Infrastructure Test Runner
# Usage: ./run-payment-tests.sh [phase|all]

set -e

echo "🔧 Payment Infrastructure Testing Suite"
echo "========================================"

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

# Phase selection
PHASE=${1:-all}

# Test environment setup
setup_test_environment() {
    echo -e "${BLUE}📋 Setting up test environment...${NC}"
    
    # Ensure test database is ready
    if [ ! -f "database/testing.sqlite" ]; then
        echo "   Creating test database..."
        touch database/testing.sqlite
    fi
    
    # Run test migrations
    echo "   Running test migrations..."
    php artisan migrate --database=testing --force
    
    # Seed test data (optional - continue if seeder doesn't exist)
    echo "   Seeding test data..."
    if php artisan db:seed --database=testing --class=PaymentTestSeeder --force 2>/dev/null; then
        echo "   ✅ Test data seeded successfully"
    else
        echo "   ⚠️  PaymentTestSeeder not found, continuing without test data"
    fi
    
    # Install test dependencies
    echo "   Installing Node dependencies..."
    npm install --silent
    
    # Validate Playwright is ready
    echo "   Validating Playwright installation..."
    npx playwright install chromium --with-deps
    
    echo -e "${GREEN}✅ Test environment ready${NC}"
}

# Phase 1: Infrastructure Audit (Documentation Review)
run_phase1() {
    echo -e "${BLUE}📊 Phase 1: Payment Infrastructure Audit${NC}"
    echo "   Reviewing existing audit documentation..."
    
    if [ -f "test-results/payment-infrastructure-audit.md" ]; then
        echo -e "${GREEN}✅ Phase 1 Complete: Infrastructure audit documented${NC}"
        echo "   📄 Report: test-results/payment-infrastructure-audit.md"
    else
        echo -e "${RED}❌ Phase 1 Missing: Infrastructure audit not found${NC}"
        return 1
    fi
}

# Phase 2: End-to-End Flow Testing  
run_phase2() {
    echo -e "${BLUE}🔄 Phase 2: End-to-End Payment Flow Testing${NC}"
    
    if [ ! -f "tests/e2e/payment-infrastructure.spec.ts" ]; then
        echo -e "${RED}❌ Phase 2 test file missing${NC}"
        return 1
    fi
    
    echo "   Running E2E payment flow tests..."
    
    # Start Laravel test server
    echo "   Starting test server..."
    php artisan serve --port=8081 --env=testing &
    SERVER_PID=$!
    
    # Wait for server to start
    sleep 3
    
    # Run Phase 2 tests
    echo "   Executing payment infrastructure tests..."
    if npx playwright test tests/e2e/payment-infrastructure.spec.ts --reporter=line; then
        echo -e "${GREEN}✅ Phase 2 Complete: E2E payment flows validated${NC}"
        PHASE2_SUCCESS=true
    else
        echo -e "${RED}❌ Phase 2 Failed: E2E payment tests failed${NC}"
        PHASE2_SUCCESS=false
    fi
    
    # Stop test server
    kill $SERVER_PID 2>/dev/null || true
    
    if [ "$PHASE2_SUCCESS" = false ]; then
        return 1
    fi
}

# Phase 3: Performance & Edge Cases
run_phase3() {
    echo -e "${BLUE}⚡ Phase 3: Performance & Edge Case Testing${NC}"
    
    if [ ! -f "tests/e2e/payment-performance.spec.ts" ]; then
        echo -e "${RED}❌ Phase 3 test file missing${NC}"
        return 1
    fi
    
    echo "   Running performance and edge case tests..."
    
    # Start Laravel test server with performance config
    echo "   Starting performance test server..."
    APP_ENV=testing php artisan serve --port=8081 &
    SERVER_PID=$!
    
    # Wait for server to start
    sleep 3
    
    # Run Phase 3 tests with longer timeout
    echo "   Executing performance tests (this may take a while)..."
    if npx playwright test tests/e2e/payment-performance.spec.ts --reporter=line --timeout=120000; then
        echo -e "${GREEN}✅ Phase 3 Complete: Performance & edge cases validated${NC}"
        PHASE3_SUCCESS=true
    else
        echo -e "${RED}❌ Phase 3 Failed: Performance tests failed${NC}"  
        PHASE3_SUCCESS=false
    fi
    
    # Stop test server
    kill $SERVER_PID 2>/dev/null || true
    
    if [ "$PHASE3_SUCCESS" = false ]; then
        return 1
    fi
}

# Generate test report
generate_report() {
    echo -e "${BLUE}📋 Generating Test Report${NC}"
    
    TIMESTAMP=$(date '+%Y-%m-%d %H:%M:%S')
    REPORT_FILE="test-results/payment-test-run-$(date '+%Y%m%d-%H%M%S').md"
    
    cat > "$REPORT_FILE" << EOF
# Payment Infrastructure Test Run Report

**Generated:** $TIMESTAMP  
**Test Phase:** $PHASE

## Test Results Summary

| Phase | Status | Description |
|-------|--------|-------------|
| Phase 1 | ✅ PASS | Infrastructure audit documented |
| Phase 2 | $([ "$PHASE2_SUCCESS" = true ] && echo "✅ PASS" || echo "❌ FAIL") | E2E payment flow testing |
| Phase 3 | $([ "$PHASE3_SUCCESS" = true ] && echo "✅ PASS" || echo "❌ FAIL") | Performance & edge case testing |

## Confidence Level

$(if [ "$PHASE2_SUCCESS" = true ] && [ "$PHASE3_SUCCESS" = true ]; then
echo "**🟢 HIGH CONFIDENCE (95%)** - Ready for SVG migration"
else
echo "**🔴 LOW CONFIDENCE** - Issues detected, resolve before proceeding"
fi)

## Test Artifacts

- Playwright HTML Report: \`playwright-report/index.html\`
- Test Screenshots: \`test-results/\`
- Infrastructure Audit: \`test-results/payment-infrastructure-audit.md\`

## Next Steps

$(if [ "$PHASE2_SUCCESS" = true ] && [ "$PHASE3_SUCCESS" = true ]; then
echo "✅ Payment infrastructure is thoroughly tested and validated
✅ Safe to proceed with SVG seat map migration  
✅ All error scenarios and recovery mechanisms verified"
else
echo "❌ Resolve failing tests before proceeding with major changes
❌ Review test artifacts for specific failure details
❌ Consider additional testing or infrastructure improvements"
fi)
EOF

    echo "   📄 Report generated: $REPORT_FILE"
}

# Main execution
main() {
    echo "Starting payment infrastructure testing..."
    echo "Phase selection: $PHASE"
    echo ""
    
    # Setup
    setup_test_environment
    
    # Initialize success tracking
    PHASE2_SUCCESS=true
    PHASE3_SUCCESS=true
    
    # Run selected phases
    case $PHASE in
        "1"|"phase1")
            run_phase1
            ;;
        "2"|"phase2")
            run_phase1
            run_phase2
            ;;
        "3"|"phase3")
            run_phase1
            run_phase2  
            run_phase3
            ;;
        "all"|*)
            run_phase1
            run_phase2
            run_phase3
            ;;
    esac
    
    # Generate report
    generate_report
    
    echo ""
    echo -e "${GREEN}🎉 Payment Infrastructure Testing Complete!${NC}"
    echo "   📊 View detailed results in: playwright-report/index.html"
    echo "   📄 Test summary: test-results/payment-testing-strategy-complete.md"
    
    if [ "$PHASE2_SUCCESS" = true ] && [ "$PHASE3_SUCCESS" = true ]; then
        echo -e "${GREEN}   ✅ READY FOR SVG MIGRATION${NC}"
        exit 0
    else
        echo -e "${RED}   ❌ RESOLVE ISSUES BEFORE PROCEEDING${NC}"
        exit 1
    fi
}

# Error handling
trap 'echo -e "${RED}❌ Test execution interrupted${NC}"; kill $SERVER_PID 2>/dev/null || true; exit 1' INT TERM

# Run main function
main
