String GITHUB_REPOSITORY = 'ows-product-digital'
String ECR_ACCOUNT_ID = '437795906767'
List<String> AWS_REGIONS = ['us-east-1']
String SLACK_NOTIFICATIONS_CHANNEL = 'content-creation-mgmt-alerts'
String QA_ACCOUNT_ID = '437795906767'
String QA_DEPLOYMENT_ROLE = 'prod-jenkins-aws-pipeline-agent'
String PROD_ACCOUNT_ID = '437795906767'
String PROD_DEPLOYMENT_ROLE = 'prod-jenkins-aws-pipeline-agent'
String BUILD_ROLE = 'qa-ows-product-digital-integration-test-role'
String SESSION_NAME = 'qa-ows-product-digital-integration-test'

List<String> VULNERABILITIES_TO_IGNORE = [
    'CVE-2023-52425',
    'CVE-2026-23949', // base image issue: pkg:pypi/jaraco.context@5.3.0
    'CVE-2026-24049', // base image issue: pkg:pypi/wheel@0.45.1
    'CVE-2026-27135', // pkg:deb/debian/nghttp2@1.52.0 - no fix available
    'CVE-2026-33164', // pkg:deb/debian/libde265@1.0.11-1+deb12u2
]

pipeline {
    agent any

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

    parameters {
        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('Build Test and Scan') {
            parallel {
                stage('Validate Software Catalog Definition') {
                    steps {
                        datadogSoftwareCatalogValidate()
                    }
                }
                stage('Unit Tests and Style Checks') {
                    environment {
                        COMPOSE_PROJECT_NAME = "${env.BUILD_TAG.toLowerCase()}"
                    }
                    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: "product-digital"]])
                        }
                        cleanup {
                            sh 'make ci_unit_lint_clean'
                        }
                    }
                }
                stage('Static Application Security Tests') {
                    steps {
                        sastTests()
                    }
                }
                stage('Sonar Scan and Analysis') {
                    when {
                        branch 'master'
                    }
                    steps {
                        sonarScan project: GITHUB_REPOSITORY, language: 'py'
                    }
                }
                stage('Create and Scan a Release') {
                    steps {
                        dockerToEcr awsRegions: AWS_REGIONS, ecrAccountId: ECR_ACCOUNT_ID, imageName: GITHUB_REPOSITORY, imageTag: env.GIT_COMMIT,
                            dockerBuildTarget: 'deploy'
                        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'
            }
            environment {
                BASE_QA_WORKSTATION_URL = 'https://workstation.qaorch.com/grass'
                QA_DB_DATABASE = 'art_relations'
                QA_DB_HOST = 'qadb01.qaorch.com'
                QA_DB_USER = 'automation_qa'
                QA_GRASS_HOST = 'https://api-dev.theorchard.io/auth/session'
            }
            steps {
                withEcr {
                    withAWS(role: BUILD_ROLE, roleAccount: QA_ACCOUNT_ID, roleSessionName: SESSION_NAME, useNode: true) {
                        withSecrets(secrets: [
                            [id: 'qa/ows-product-digital/AUTOMATION_QA_DB_PASS', environmentVariable: 'QA_DB_PASS'],
                        ]) {
                            sh 'make ci_test_integration'
                        }
                    }
                }
            }
            post {
                cleanup {
                    sh 'make ci_test_integration_clean'
                }
            }
        }
        stage('E2E Tests') {
            when {
                branch 'master'
            }
            environment {
                TAGS = "@ows_product_digital"
            }
            steps {
                sleep(10)
                playwrightTests tags: env.TAGS
            }
        }
        stage('Deploy to Prod') {
            when {
                allOf {
                    branch 'master'
                    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()
        }
    }
}
