String GITHUB_REPOSITORY = 'graphql-content-review'
String ECR_ACCOUNT_ID = '437795906767'
String QA_ACCOUNT_ID = '437795906767'
String PROD_ACCOUNT_ID = '437795906767'
List<String> AWS_REGIONS = ['us-east-1']
String QA_DEPLOYMENT_ROLE = 'prod-jenkins-aws-pipeline-agent'
String PROD_DEPLOYMENT_ROLE = 'prod-jenkins-aws-pipeline-agent'
String SLACK_NOTIFICATIONS_CHANNEL = '#graphql, #content-review-team'

List<String> VULNERABILITIES_TO_IGNORE = [
    'CVE-2024-28182', // Unfixed upstream (node20 image)
    'CVE-2024-21538',
    'CVE-2023-42282',
    'CVE-2025-7783', // node-form-data: present in base image
    'CVE-2025-9230',
    'CVE-2026-25896',
    'CVE-2026-23897',
    'CVE-2026-2391',
    'CVE-2026-24001',
    'CVE-2026-4800',
    'CVE-2026-33036',
    'CVE-2026-4867',
    'CVE-2026-4926',
    'CVE-2025-13465' // pkg:npm/lodash@4.17.21
]

pipeline {
    agent any

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

    parameters {
        booleanParam(name: 'DEPLOY_TO_PROD', defaultValue: true, description: 'Whether or not to deploy to prod.')
        booleanParam(name: 'VALIDATE_SCHEMA', defaultValue: true, description: 'Whether or not to validate schema.')
        string(name: 'SHARED_LIBRARIES_VERSION', defaultValue: 'master', description: 'The version of the Jenkins shared libraries to use. Can be a branch, tag or Git revision.')
    }

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

    stages {
        stage('Load Shared Libraries') {
            steps {
                library "jenkins-global-libraries@${params.SHARED_LIBRARIES_VERSION}"
            }
        }
        stage('Checks and Static Tests') {
            parallel {
                stage('Compliance Checks') {
                    steps {
                        complianceChecks()
                    }
                }
                stage('Validate Software Catalog Definition') {
                    steps {
                        datadogSoftwareCatalogValidate()
                    }
                }
                stage('Static Application Security Tests') {
                    steps {
                        sastTests()
                    }
                }
                stage('Sonar Scan and Analysis') {
                    when {
                        branch 'master'
                    }
                    steps {
                        sonarScan project: GITHUB_REPOSITORY, language: 'ts', exclusions: 'tests/** , **/__tests__/**'
                    }
                }
                stage('Unit tests and Style Checks') {
                    steps {
                        withCredentials([string(credentialsId: 'github_packages_token', variable: 'GITHUB_NPM_TOKEN'),]) {
                            withEcr {
                                sh 'docker compose run --build --rm lint-and-test'
                            }
                        }
                    }
                }
                stage('Validate QA schema') {
                    when {
                        expression {
                            params.VALIDATE_SCHEMA == true
                        }
                    }
                    steps {
                        graphqlPushSchema environment: 'qa', roverOperation: 'check', serviceName: GITHUB_REPOSITORY
                    }
                }
            }
        }
        stage('Create a release') {
            when {
                branch 'master'
            }
            steps {
                withCredentials([string(credentialsId: 'github_packages_token', variable: 'GITHUB_NPM_TOKEN')]) {
                    dockerToEcr awsRegions: AWS_REGIONS, ecrAccountId: ECR_ACCOUNT_ID, imageName: GITHUB_REPOSITORY,
                        imageTag: env.GIT_COMMIT, dockerBuildSecrets: [[id: 'github_npm_token', env: 'GITHUB_NPM_TOKEN']], dockerBuildTarget: 'deploy'
                }
            }
        }
        stage('Deploying 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('Push QA Schema and Scan Docker Image') {
            when {
                branch 'master'
            }
            parallel {
                stage('Push QA schema') {
                    steps {
                        graphqlPushSchema environment: 'qa', roverOperation: 'publish', serviceName: GITHUB_REPOSITORY
                    }
                }
                stage('Scan Docker Image') {
                    steps {
                        dockerScan awsRegion: AWS_REGIONS[0], ecrAccountId: ECR_ACCOUNT_ID, imageName: GITHUB_REPOSITORY, imageTag: env.GIT_COMMIT,
                            vulnerabilitiesToIgnore: VULNERABILITIES_TO_IGNORE
                    }
                }
            }
        }
        stage('Integration Tests') {
            environment {
                BASE_URL = 'https://qa-graphql-content-review.theorchard.io/graphql'
            }
            when {
                branch 'master'
            }
            parallel {
                stage('Service Integration Tests') {
                    steps {
                        withCredentials([
                            string(credentialsId: 'github_packages_token', variable: 'GITHUB_NPM_TOKEN')
                        ]) {
                            withEcr {
                                sh 'docker compose run --build --rm integration-tests'
                            }
                        }
                    }
                }
                stage('Gateway Integration Tests') {
                    steps {
                        retry(2) {
                            echo 'Running gateway integration tests...'
                            build job: 'graphql-gateway-integration-tests'
                        }
                    }
                }
            }
        }
        stage('E2E Tests') {
            when {
                branch 'master'
            }
            steps {
                playwrightTests(tags: '@content_review', reportSuffix: 'contentReview', slackNotificationChannels: ['#content-review-team'])
            }
        }
        stage('Validate Prod schema') {
            when {
                expression {
                    params.VALIDATE_SCHEMA == true
                }
            }
            steps {
                graphqlPushSchema environment: 'prod', roverOperation: 'check', serviceName: GITHUB_REPOSITORY
            }
        }
        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()
            }
        }
        stage('Push Prod schema') {
            when {
                allOf {
                    branch 'master'
                    expression { params.DEPLOY_TO_PROD }
                }
            }
            steps {
                graphqlPushSchema environment: 'prod', roverOperation: 'publish', serviceName: GITHUB_REPOSITORY
            }
        }
    }
    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()
        }
    }
}
