pipeline {
    agent {
        docker {
            image 'registry.example.invalid/ci/node:20'
            args '-u 1000:1000'
        }
    }

    options {
        timeout(time: 30, unit: 'MINUTES')
        buildDiscarder(logRotator(numToKeepStr: '20'))
        disableConcurrentBuilds()
    }

    environment {
        BUILD_DIR = 'build'
        REGISTRY  = 'registry.example.invalid'
    }

    parameters {
        choice(name: 'ENVIRONMENT', choices: ['staging', 'production'], description: 'Target')
        booleanParam(name: 'RUN_INTEGRATION', defaultValue: false, description: 'Slow suite')
    }

    stages {
        stage('Install') {
            steps {
                sh 'npm ci'
            }
        }

        stage('Build') {
            steps {
                sh "npm run build -- --out ${env.BUILD_DIR}"
            }
        }

        stage('Test') {
            parallel {
                stage('Unit') {
                    steps {
                        sh 'npm run test:unit'
                    }
                }
                stage('Integration') {
                    when {
                        expression { return params.RUN_INTEGRATION }
                    }
                    steps {
                        sh 'npm run test:integration'
                    }
                }
            }
        }
    }

    post {
        always {
            junit 'reports/junit.xml'
        }
        failure {
            echo "build ${env.BUILD_NUMBER} failed"
        }
    }
}
