node {
    try {
        stage('Checkout') {
            checkout scm
        }

        stage('Check Environment') {
            sh 'mvn -v'
            sh 'java -version'
        }

        stage('Build') {
            sh 'mvn clean package -DskipTests'
        }

        stage('Test') {
            sh 'mvn test || true'
            script {
                if (fileExists('target/surefire-reports')) {
                    junit allowEmptyResults: true, testResults: 'target/surefire-reports/*.xml'
                } else {
                    echo '⚠️ No test reports found — skipping JUnit report'
                }
            }
        }

        stage('Code Quality') {
            withSonarQubeEnv('SonarQube') {
                sh """
                    mvn sonar:sonar \
                        -Dsonar.projectKey=server \
                        -Dsonar.projectName='Taxi App - Server' \
                        -Dsonar.coverage.jacoco.xmlReportPaths=target/site/jacoco/jacoco.xml
                """
            }
        }

        stage('Quality Gate') {
            timeout(time: 5, unit: 'MINUTES') {
                def qg = waitForQualityGate()
                if (qg.status != 'OK') {
                    echo "⚠️ Quality Gate status: ${qg.status} — continuing for now"
                }
            }
        }

        stage('Deploy') {
            sh 'sudo systemctl daemon-reload'
            sh 'sudo systemctl enable camelsofttaxibackend'
            sh 'sudo systemctl restart camelsofttaxibackend'
            sleep(10)
            sh 'sudo systemctl status camelsofttaxibackend --no-pager'
        }

    } catch (Exception e) {
        echo "Pipeline failed: ${e.getMessage()}"
        throw e
    }
}