String GITHUB_REPOSITORY = 'graphql-switchboard'
String ECR_ACCOUNT_ID = '437795906767'
List<String> AWS_REGIONS = ['us-east-1']
String SLACK_NOTIFICATIONS_CHANNEL = '#switchboard'
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 INTEGRATION_TEST_ROLE = 'qa-graphql-switchboard-integration-test-role'

List<String> VULNERABILITIES_TO_IGNORE = [
    'CVE-2021-23326',   // @graphql-tools/git-loader
    'CVE-2024-29415',   // ip/node
    'CVE-2026-23897',   // apollo-server@3.x - no fix in v3; requires migration to Apollo Server 4
    'CVE-2026-41907',   // pkg:npm/uuid@9.0.1
    'CVE-2026-48959',  // pkg:deb/debian/perl@5.36.0-7%2Bdeb12u3
    'CVE-2026-48961',  // pkg:deb/debian/perl@5.36.0-7%2Bdeb12u3
    'CVE-2026-48962',  // pkg:deb/debian/perl@5.36.0-7%2Bdeb12u3

    'CVE-2026-33750',  // pkg:npm/brace-expansion@2.0.2 . Need to replace eslint-config-airbnb-base with prettier and update jest for it to work.
    'CVE-2026-33671',  // pkg:npm/picomatch@4.0.3 . Needs to be fixed by nodemon@3.1.14
]

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 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') {
                    steps {
                        sonarScan project: GITHUB_REPOSITORY, language: 'js', exclusions: 'tests/** , lib/test-helpers/**, **/__tests__/**'
                    }
                }
                stage('Unit tests and Style Checks') {
                    steps {
                        withCredentials([string(credentialsId: 'github_packages_token', variable: 'GITHUB_NPM_TOKEN'),]) {
                            withEcr {
                                sh '''
                                docker compose up --build \
                                    --exit-code-from unit-lint \
                                    --abort-on-container-exit \
                                    --remove-orphans \
                                    unit-lint
                                '''
                            }
                        }
                    }
                    post {
                        cleanup {
                            sh 'docker compose down'
                        }
                    }
                }
            }
        }
        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('Scan Docker Image') {
            when {
                branch 'master'
            }
            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-switchboard.theorchard.io/graphql'
            }
            when {
                branch 'master'
            }
            parallel {
                stage('Service Integration Tests') {
                    steps {
                        retry(2) {
                            withCredentials([
                                string(credentialsId: 'github_packages_token', variable: 'GITHUB_NPM_TOKEN'),
                            ]) {
                                withEcr {
                                    withAWS(
                                        role: INTEGRATION_TEST_ROLE,
                                        roleAccount: QA_ACCOUNT_ID,
                                        roleSessionName: "${params.Environment}-graphql-switchboard-integration-test",
                                        useNode: true
                                    ) {
                                        sh '''
                                        docker compose up --build \
                                            --exit-code-from integration-tests \
                                            --abort-on-container-exit \
                                            --remove-orphans \
                                            integration-tests
                                        '''
                                    }
                                }
                            }
                        }
                    }
                }
            }
            post {
                cleanup {
                    sh 'docker compose down'
                }
            }
        }
        stage('E2E Tests') {
            when {
                branch 'master'
            }
            environment {
                // Using smoke tests for now, coverage needs to be reviewed
                TAGS = "@qa_smoke"
            }
            steps {
                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()
        }
    }
}
