String GITHUB_REPOSITORY = 'graphql-neighbouring-rights'
String ECR_ACCOUNT_ID = '086679231553'
List<String> AWS_REGIONS = ['us-east-1']
String SLACK_NOTIFICATIONS_CHANNEL = '#graphql'
String QA_ACCOUNT_ID = '437795906767'
String QA_DEPLOYMENT_ROLE = 'prod-jenkins-aws-pipeline-agent'
String QA_INTEGRATION_TEST_ROLE = 'qa-graphql-neighbouring-rights-integration-test-role'
String PROD_ACCOUNT_ID = '437795906767'
String PROD_DEPLOYMENT_ROLE = 'prod-jenkins-aws-pipeline-agent'

List<String> VULNERABILITIES_TO_IGNORE = [
    'CVE-2025-65945',
    'CVE-2025-69873',
    'CVE-2026-23897',
    'CVE-2026-2391',
    'CVE-2026-25128',
    'CVE-2026-25639',
    'CVE-2026-27903',
    'CVE-2026-27904',
    'CVE-2026-27942',
    'CVE-2026-26278',
    'CVE-2026-26960',
    'CVE-2026-26996',
    'CVE-2026-25896',
    'CVE-2025-62718',
    'CVE-2026-29063',
    'CVE-2026-32621',
    'CVE-2026-41242',
    'CVE-2026-42043',
    'CVE-2026-42044',
    'CVE-2026-42264',
    'CVE-2026-4800',
    'CVE-2026-9277',
    'CVE-2025-13465',
    'CVE-2026-23745',
    'CVE-2026-23950',
    'CVE-2026-24842',
    'CVE-2026-29786',
    'CVE-2026-31802',
    'CVE-2026-33036',
    'CVE-2026-33671',
    'CVE-2026-33750',
    'CVE-2026-41907',
    'CVE-2026-42033',
    'CVE-2026-42035',
    'CVE-2026-42038',
    'CVE-2026-42039',
    'CVE-2026-44289',
    'CVE-2026-44290',
    'CVE-2026-44291',
    'CVE-2026-44293',
    'CVE-2026-45149',
    'CVE-2026-45736',
    'CVE-2026-45740',
    'CVE-2026-4867',
    'CVE-2026-4926',
    // form-data@3.0.4 — fixed in 3.0.5 (transitive dep, internal lambda)
    'CVE-2026-12143',
    // axios@1.12.2 — fixed in 1.15.2/1.16.0 (internal lambda, no user-facing attack surface)
    'CVE-2026-44486',
    'CVE-2026-44487',
    'CVE-2026-44488',
    'CVE-2026-44490',
    'CVE-2026-44492',
    'CVE-2026-44494',
    'CVE-2026-44495',
    'CVE-2026-44496',
]

pipeline {
    agent any

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

    parameters {
        // Testing CRP-29 in QA only
        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.')
        booleanParam(name: 'RUN_E2E_TESTS', defaultValue: true, description: 'Whether or not to run the Playwright E2E tests. Temporarily disable (uncheck) to deploy while E2E is known-broken — see NR-3196.')
        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('Checks and Static Tests') {
            parallel {
                stage('Compliance Checks') {
                    steps {
                        complianceChecks()
                    }
                }
                stage('Validate Software Catalog Definition') {
                    steps {
                        datadogSoftwareCatalogValidate()
                    }
                }
                stage('Sonar Scan and Analysis') {
                    steps {
                        sonarScan project: GITHUB_REPOSITORY, language: 'ts', exclusions: '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 \
                                --exit-code-from lint-and-test \
                                --build \
                                --abort-on-container-exit \
                                --remove-orphans \
                                lint-and-test
                                '''
                            }
                        }
                    }
                    post {
                        cleanup {
                            sh 'docker compose down -v'
                        }
                    }
                }
                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('Integration Tests') {
            when {
                branch 'master'
            }

            environment {
                NODE_OPTIONS = "-r dd-trace/ci/init"
                DD_GIT_COMMIT_AUTHOR_NAME = sh(script: 'git log -1 --pretty=%an', returnStdout: true).trim()
                DD_GIT_COMMIT_AUTHOR_EMAIL = sh(script: 'git log -1 --pretty=%ae', returnStdout: true).trim()
                DD_GIT_COMMIT_AUTHOR_DATE = sh(script: 'git log -1 --pretty=%aI', returnStdout: true).trim()
            }

            // Required to reach dev kafka brokers
            agent { label 'can_reach_orchard_aws_dev' }
            steps {
                retry(2) {
                    withSecrets(
                            awsAccountId: PROD_ACCOUNT_ID,
                            awsRole: QA_INTEGRATION_TEST_ROLE,
                            secrets: [
                                [id: 'qa/graphql-neighbouring-rights/KSQL_CREDS', environmentVariable: 'KSQL_CREDS'],
                                [id: 'qa/graphql-neighbouring-rights/SFORCE_REFRESH_TOKEN', environmentVariable: 'SFORCE_REFRESH_TOKEN'],
                                [id: 'qa/graphql-neighbouring-rights/SFORCE_CLIENT_ID', environmentVariable: 'SFORCE_CLIENT_ID'],
                                [id: 'qa/graphql-neighbouring-rights/SFORCE_CLIENT_SECRET', environmentVariable: 'SFORCE_CLIENT_SECRET'],
                            ]
                        ){
                            withCredentials([
                                string(credentialsId: 'github_packages_token', variable: 'GITHUB_NPM_TOKEN'),
                                string(credentialsId: 'split.io-api-key', variable: 'SPLIT_API_KEY'),
                            ]) {
                                withEcr {
                                    withAWS(role: QA_INTEGRATION_TEST_ROLE, roleAccount: PROD_ACCOUNT_ID, useNode: true) {
                                        sh '''
                                        docker compose up \
                                        --build \
                                        --exit-code-from integration-tests \
                                        --abort-on-container-exit \
                                        --remove-orphans \
                                        --attach-dependencies \
                                        integration-tests
                                        '''
                                    }
                                }
                            }

                        }

                }
            }
            post {
                cleanup {
                    sh 'docker compose down -v'
                }
            }
        }
        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('E2E Tests') {
            when {
                allOf {
                    branch 'master'
                    expression { params.RUN_E2E_TESTS }
                }
            }
            steps {
                playwrightTests(tags: '@contentNeighbouringRights', slackNotificationChannels: ['#content-nr-tech'])
            }
        }
        stage('Validate Prod schema') {
           when {
               allOf {
                   branch 'master'
                   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 == true }
              }
          }
          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 == true }
              }
          }
          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()
        }
    }
}
