pipeline {
    agent any

    tools {
        gradle 'gradle-9.3.1'
    }

    environment {
        GRADLE_USER_HOME = '/var/jenkins_home/.gradle'
        GRADLE_OPTS = '-Dorg.gradle.parallel=true -Dorg.gradle.caching=true'
        JAVA_OPTS = '-Xmx2g'
    }

    stages {
        stage('Build') {
            steps {
                withChecks(name: 'Test', includeStage: true) {
                    withGradle {
                        sh """
                            gradle \
                                clean \
                                test \
                                jacocoTestReport \
                                --parallel \
                                --max-workers=2 \
                                --build-cache \
                                --no-daemon
                        """
                    }
                    recordCoverage(tools: [[parser: 'JACOCO', pattern: "build/reports/jacoco/jacocoTestReport/jacocoTestReport.xml"]],
                        id: 'jacoco',
                        name: 'JaCoCo Coverage',
                        sourceCodeRetention: 'EVERY_BUILD',
                        qualityGates: [
                            [threshold: 50.0, metric: 'CLASS', baseline: 'PROJECT', unstable: true],
                            [threshold: 50.0, metric: 'METHOD', baseline: 'PROJECT', unstable: true],
                            [threshold: 50.0, metric: 'LINE', baseline: 'PROJECT', unstable: true],
                            [threshold: 50.0, metric: 'INSTRUCTION', baseline: 'PROJECT', unstable: true],
                            [threshold: 40.0, metric: 'BRANCH', baseline: 'PROJECT', unstable: true]])
                    junit testResults: '**/build/test-results/test/TEST-*.xml'
                }
            }
        } // Test

        stage('Reports') {
            steps {
                script {
                    // archiveArtifacts artifacts: '**/coverage-sources.zip', allowEmptyArchive: false, fingerprint: false, onlyIfSuccessful: false
                    publishHTML (target: [
                        allowMissing: true,
                        alwaysLinkToLastBuild: false,
                        keepAll: true,
                        reportDir: "build/reports/jacoco/jacocoTestReport/html",
                        reportFiles: 'index.html',
                        reportName: 'Coverage Report'
                    ])
                    // def pmd = scanForIssues tool: [$class: 'Pmd'], pattern: 'lib/build/reports/pmd/*.xml'
                    // publishIssues issues: [pmd]
                }
            }
        } // Reports
    }
}