String GITHUB_REPOSITORY = 'ows-product-workflow'
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-workflow-integration-test-role'

List<String> VULNERABILITIES_TO_IGNORE = [
    'CVE-2023-52356',
    'CVE-2023-52425', // Debian libexpat through 2.5.0 allows a denial of service. Not fixed yet
    'CVE-2024-7006',
    'CVE-2025-66418', // urllib3
    'CVE-2025-66471',  // urllib3
    '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-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('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: false, sourceDirectories: [[path: "product_workflow"]])
                }
                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 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('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('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('Integration Tests') {
        //     when {
        //         branch 'master'
        //     }
        //     environment {
        //         BASE_QA_GRASS_URL = 'https://workstation.qaorch.com/grass'
        //         BASE_QA_URL = 'https://qa-ows-product-workflow.theorchard.io'
        //         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(roleAccount: '437795906767', role: BUILD_ROLE, roleSessionName: env.BUILD_TAG, useNode: true) {
        //                 withSecrets(secrets: [
        //                     [id: 'qa/ows-product-workflow/AUTOMATION_QA_DB_PASS', environmentVariable: 'QA_DB_PASS'],
        //                 ]) {
        //                     sh 'make ci_test_integration'
        //                 }
        //             }
        //         }
        //     }
        // }
        stage('E2E Tests') {
            when {
                branch 'master'
            }
            environment {
                TAGS = "@ows_product_workflow"
            }
            steps {
                sleep(10)
                playwrightTests tags: env.TAGS, slackNotificationChannels: [SLACK_NOTIFICATIONS_CHANNEL]
            }
        }
        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()
        }
    }
}
