pipeline {
    agent any
    
    environment {
        APP_ENV = 'testing'
        DB_CONNECTION = 'mysql'
        DB_HOST = 'mysql'
        DB_PORT = '3306'
        DB_DATABASE = 'ffr_testing'
        DB_USERNAME = 'ffr_user'
        DB_PASSWORD = 'ffr_password'
        CACHE_STORE = 'array'
        SESSION_DRIVER = 'array'
        QUEUE_CONNECTION = 'sync'
    }
    
    stages {
        stage('Checkout') {
            steps {
                checkout scm
            }
        }
        
        stage('Setup Environment') {
            steps {
                script {
                    sh '''
                        echo "Setting up environment for testing..."
                        cp .env.example .env.testing
                        echo "APP_ENV=testing" >> .env.testing
                        echo "DB_CONNECTION=${DB_CONNECTION}" >> .env.testing
                        echo "DB_HOST=${DB_HOST}" >> .env.testing
                        echo "DB_PORT=${DB_PORT}" >> .env.testing
                        echo "DB_DATABASE=${DB_DATABASE}" >> .env.testing
                        echo "DB_USERNAME=${DB_USERNAME}" >> .env.testing
                        echo "DB_PASSWORD=${DB_PASSWORD}" >> .env.testing
                        echo "CACHE_STORE=${CACHE_STORE}" >> .env.testing
                        echo "SESSION_DRIVER=${SESSION_DRIVER}" >> .env.testing
                        echo "QUEUE_CONNECTION=${QUEUE_CONNECTION}" >> .env.testing
                    '''
                }
            }
        }
        
        stage('Install Dependencies') {
            parallel {
                stage('PHP Dependencies') {
                    steps {
                        sh '''
                            echo "Installing PHP dependencies..."
                            composer install --no-interaction --prefer-dist --optimize-autoloader --no-dev
                        '''
                    }
                }
                stage('Node Dependencies') {
                    steps {
                        sh '''
                            echo "Installing Node.js dependencies..."
                            npm ci
                        '''
                    }
                }
            }
        }
        
        stage('Generate Application Key') {
            steps {
                sh '''
                    php artisan key:generate --env=testing --force
                '''
            }
        }
        
        stage('Database Setup') {
            steps {
                sh '''
                    echo "Setting up test database..."
                    php artisan migrate:fresh --env=testing --force
                    php artisan config:clear --env=testing
                '''
            }
        }
        
        stage('Code Quality Checks') {
            parallel {
                stage('PHP Syntax Check') {
                    steps {
                        sh '''
                            echo "Checking PHP syntax..."
                            find . -name "*.php" -not -path "./vendor/*" -not -path "./node_modules/*" -exec php -l {} \\;
                        '''
                    }
                }
                stage('PHPStan Analysis') {
                    steps {
                        script {
                            try {
                                sh '''
                                    if [ -f "phpstan.neon" ]; then
                                        echo "Running PHPStan static analysis..."
                                        ./vendor/bin/phpstan analyse --no-progress --error-format=table
                                    else
                                        echo "PHPStan configuration not found, skipping static analysis"
                                    fi
                                '''
                            } catch (Exception e) {
                                unstable(message: "PHPStan found issues")
                            }
                        }
                    }
                }
                stage('Security Audit') {
                    steps {
                        script {
                            try {
                                sh '''
                                    echo "Running security audit..."
                                    composer audit
                                '''
                            } catch (Exception e) {
                                unstable(message: "Security vulnerabilities found")
                            }
                        }
                    }
                }
            }
        }
        
        stage('Unit Tests') {
            steps {
                sh '''
                    echo "Running Unit Tests..."
                    php artisan test tests/Unit/ --env=testing --stop-on-failure
                '''
            }
            post {
                always {
                    publishTestResults testResultsPattern: 'tests/Unit/results/*.xml'
                }
            }
        }
        
        stage('Feature Tests') {
            steps {
                sh '''
                    echo "Running Feature Tests..."
                    php artisan test tests/Feature/ --env=testing --stop-on-failure
                '''
            }
            post {
                always {
                    publishTestResults testResultsPattern: 'tests/Feature/results/*.xml'
                }
            }
        }
        
        stage('Full Regression Test Suite') {
            steps {
                sh '''
                    echo "Running comprehensive regression test suite..."
                    chmod +x ./run-regression-tests.sh
                    ./run-regression-tests.sh
                '''
            }
            post {
                always {
                    // Archive test results
                    archiveArtifacts artifacts: 'tests/reports/**/*', allowEmptyArchive: true
                    
                    // Publish coverage reports if available
                    publishHTML([
                        allowMissing: false,
                        alwaysLinkToLastBuild: true,
                        keepAll: true,
                        reportDir: 'coverage',
                        reportFiles: 'index.html',
                        reportName: 'Coverage Report'
                    ])
                }
            }
        }
        
        stage('Performance Tests') {
            steps {
                script {
                    try {
                        sh '''
                            echo "Running performance tests..."
                            
                            # Test memory usage
                            php -d memory_limit=256M artisan test tests/Feature/DatabaseIntegrationTest.php --env=testing
                            
                            # Test response times for API endpoints
                            time php artisan test tests/Feature/ApiEndpointRegressionTest.php --env=testing
                        '''
                    } catch (Exception e) {
                        unstable(message: "Performance tests indicated potential issues")
                    }
                }
            }
        }
        
        stage('Build Assets') {
            when {
                anyOf {
                    branch 'main'
                    branch 'develop'
                }
            }
            steps {
                sh '''
                    echo "Building production assets..."
                    npm run build
                '''
            }
        }
    }
    
    post {
        always {
            // Clean up
            sh '''
                echo "Cleaning up..."
                rm -f .env.testing
            '''
        }
        success {
            echo '✅ All regression tests passed successfully!'
            // Notify success (customize as needed)
            // slackSend channel: '#dev-team', color: 'good', message: "Regression tests passed for ${env.JOB_NAME} - ${env.BUILD_NUMBER}"
        }
        failure {
            echo '❌ Regression tests failed!'
            // Notify failure (customize as needed)
            // slackSend channel: '#dev-team', color: 'danger', message: "Regression tests failed for ${env.JOB_NAME} - ${env.BUILD_NUMBER}"
        }
        unstable {
            echo '⚠️ Tests completed with warnings'
        }
    }
}