String GITHUB_REPOSITORY = 'ows-payment'
String ECR_ACCOUNT_ID = '086679231553'
List<String> AWS_REGIONS = ['us-east-1']
String SLACK_NOTIFICATIONS_CHANNEL = '#documents-public'
String QA_ACCOUNT_ID = '437795906767'
String QA_DEPLOYMENT_ROLE = 'prod-jenkins-aws-pipeline-agent'
String INTEGRATION_TEST_ROLE = 'qa-ows-payment-integration-test-role'
String SESSION_NAME = 'qa-ows-payment-integration-test'
String UAT_ACCOUNT_ID = '989790945997'
String UAT_DEPLOYMENT_ROLE = 'uat-jenkins-pipeline-deploy-role'
String PROD_ACCOUNT_ID = '437795906767'
String PROD_DEPLOYMENT_ROLE = 'prod-jenkins-aws-pipeline-agent'

List<String> VULNERABILITIES_TO_IGNORE = [
    'CVE-2022-42969',   // pkg:pypi/py@1.11.0 dev-only dep, not installed in prod venv
    'CVE-2026-23949',   // pkg:pypi/jaraco.context@5.3.0 (transitive dep, Docker cache issue)
    'CVE-2026-24049'    // pkg:pypi/wheel@0.45.1 (transitive dep, Docker cache issue)
]

pipeline {
    agent any

    options {
        ansiColor('xterm')
        disableConcurrentBuilds()
        timestamps()
    }

    parameters {
        booleanParam(name: 'DEPLOY_TO_UAT', defaultValue: true, description: 'Whether or not to deploy to uat.')
        booleanParam(name: 'DEPLOY_TO_PROD', defaultValue: true, description: 'Whether or not to deploy to prod.')
        string(name: 'SHARED_LIBRARIES_VERSION', defaultValue: 'master', description: 'The version of the Jenkins shared libraries to use. Can be a branch, tag, Git revision or PR ref (e.g. pull/PR_NUMBER/merge).')
    }

    triggers {
        issueCommentTrigger('.*retest this please.*')
    }

    stages {
        stage('Load Shared Libraries') {
            steps {
                library "jenkins-global-libraries@${params.SHARED_LIBRARIES_VERSION}"
            }
        }
        stage('Compliance Checks') {
            steps {
                complianceChecks()
            }
        }
        stage('Validate Software Catalog Definition') {
            steps {
                datadogSoftwareCatalogValidate()
            }
        }
        stage('Unit Tests and Style Checks') {
            steps {
                withEcr{
                    sh 'make ci_unit_lint'
                }
            }
            post {
                always {
                    xunit tools: [JUnit(pattern: 'build/pyunit.xml', deleteOutputFiles: true, failIfNotNew: true, stopProcessingIfError: true)]
                    recordCoverage(tools: [[parser: 'COBERTURA', pattern: 'build/coverage.xml']], enabledForFailure: true, failOnError: true, sourceDirectories: [[path: "payment"]])
                }
                cleanup {
                    sh 'make ci_unit_lint_clean'
                }
            }
        }
        stage('Static Application Security Tests') {
            steps {
                sastTests(v2: true)
            }
        }
        stage('Sonar Scan and Analysis') {
            when {
                branch 'master'
            }
            steps {
                sonarScan project: GITHUB_REPOSITORY, language: 'py'
            }
        }
        stage('Create a Release') {
            when {
                anyOf {
                    branch 'master'
                    expression { env.GITHUB_COMMENT =~ 'build docker' }
                }
            }
            steps {
                dockerToEcr awsRegions: AWS_REGIONS, ecrAccountId: ECR_ACCOUNT_ID, imageName: GITHUB_REPOSITORY, imageTag: env.GIT_COMMIT,
                    dockerBuildTarget: 'deploy'
            }
        }
        stage('Scan Docker Image') {
            when {
                anyOf {
                    branch 'master'
                    expression { env.GITHUB_COMMENT =~ 'build docker' }
                }
            }
            steps {
                dockerScan awsRegion: AWS_REGIONS[0],
                    ecrAccountId: ECR_ACCOUNT_ID,
                    imageName: GITHUB_REPOSITORY,
                    imageTag: env.GIT_COMMIT,
                    vulnerabilitiesToIgnore: VULNERABILITIES_TO_IGNORE
            }
        }
        stage('Deploy to QA') {
            when {
                branch 'master'
            }
            steps {
                fargateDeploy environment: 'qa', awsRegions: AWS_REGIONS, gitCommit: env.GIT_COMMIT, serviceName: GITHUB_REPOSITORY,
                    ecrRegistryAccountId: ECR_ACCOUNT_ID, awsDeploymentTargetAccountId: QA_ACCOUNT_ID, awsDeploymentRoleName: QA_DEPLOYMENT_ROLE
            }
        }
        stage('Integration Tests') {
            when {
                branch 'master'
            }
            steps {
                withEcr {
                    withAWS(role: INTEGRATION_TEST_ROLE, roleAccount: QA_ACCOUNT_ID, roleSessionName: SESSION_NAME, useNode: true) {
                        sh 'make ci_test_integration'
                    }
                }
            }
            post {
                cleanup {
                    sh 'make ci_test_integration_clean'
                }
            }
        }
        stage('E2E Tests') {
            when {
                branch 'master'
            }
            steps {
                playwrightTests tags: '@ows_payment', reportSuffix: 'advances_payments_results'
            }
        }
        stage('E2E Closing Balances Tests') {
            when {
                branch 'master'
            }
            steps {
                lock(resource: 'e2e-tests-documents') {
                    playwrightTests tags: '@ows_payment_closing_balances', reportSuffix: 'closing-balances-results', runtimeEnvironment: 'ecs'
                }
            }
        }
        stage('Deploy to UAT and Prod') {
            when {
                branch 'master'
            }
            parallel {
                stage('Deploy to UAT') {
                    when {
                        expression { params.DEPLOY_TO_UAT }
                    }
                    steps {
                        catchError(buildResult: 'UNSTABLE', stageResult: 'FAILURE') {
                            fargateDeploy environment: 'uat', awsRegions: AWS_REGIONS, gitCommit: env.GIT_COMMIT, serviceName: GITHUB_REPOSITORY,
                                ecrRegistryAccountId: ECR_ACCOUNT_ID, awsDeploymentTargetAccountId: UAT_ACCOUNT_ID, awsDeploymentRoleName: UAT_DEPLOYMENT_ROLE
                        }
                    }
                }
                stage('Deploy to Prod') {
                    when {
                        expression { params.DEPLOY_TO_PROD }
                    }
                    steps {
                        fargateDeploy environment: 'prod', awsRegions: AWS_REGIONS, gitCommit: env.GIT_COMMIT, serviceName: GITHUB_REPOSITORY,
                            ecrRegistryAccountId: ECR_ACCOUNT_ID, awsDeploymentTargetAccountId: PROD_ACCOUNT_ID, awsDeploymentRoleName: PROD_DEPLOYMENT_ROLE
                        datadogSoftwareCatalogPublish()
                    }
                }
            }
        }
    }

    post {
        regression {
            script {
                if (env.BRANCH_NAME == 'master') {
                    slackNotify channel: SLACK_NOTIFICATIONS_CHANNEL
                }
            }
        }
        fixed {
            script {
                if (env.BRANCH_NAME == 'master') {
                    slackNotify channel: SLACK_NOTIFICATIONS_CHANNEL
                }
            }
        }
        cleanup {
            cleanWs()
        }
    }
}
