String GITHUB_REPOSITORY = 'graphql-audience'
String ECR_ACCOUNT_ID = '086679231553'
List<String> AWS_REGIONS = ['us-east-1']
String SLACK_NOTIFICATIONS_CHANNEL = '#fansifter-alerts'
String SLACK_BUILDS_CHANNEL = '#fansifter-builds'
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'

List<String> VULNERABILITIES_TO_IGNORE = [
    "CVE-2026-34182", // openssl 3.5.6 -> 3.5.7 (bundled in Node binary)
    "CVE-2026-45149"  // brace-expansion 5.0.5 -> 5.0.6 (bundled in global npm)
]

def isSchemaChanged() {
    return getModifiedPaths(paths: ['src/schema']) as boolean
}

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.')
        choice(name: 'SKIP_E2E_TESTS', choices: ['No', 'Yes'], description: 'Whether or not to skip e2e tests step')
        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('Static Application Security Tests') {
                    steps {
                        sastTests()
                    }
                }
                stage('Sonar Scan and Analysis') {
                    steps {
                        sonarScan project: GITHUB_REPOSITORY, language: 'ts', 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 lint-and-test \
                                --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 && isSchemaChanged() }
                    }
                    steps {
                        graphqlPushSchema environment: 'qa', roverOperation: 'check', serviceName: GITHUB_REPOSITORY
                    }
                }
                stage('Validate Software Catalog Definition') {
                    steps {
                        datadogSoftwareCatalogValidate()
                    }
                }
            }
        }
        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') {
            when {
                branch 'master'
            }
            parallel {
                // stage('Service Integration Tests') {
                //     environment {
                //         NODE_OPTIONS = "--import dd-trace/register.js -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()
                //     }
                //     steps {
                //         retry(2) {
                //             withCredentials([string(credentialsId: 'github_packages_token', variable: 'GITHUB_NPM_TOKEN'),]) {
                //                 withEcr {
                //                     sh '''
                //                     docker compose up --build \
                //                     --exit-code-from integration-tests \
                //                     --abort-on-container-exit \
                //                     --remove-orphans \
                //                     integration-tests
                //                     '''
                //                 }
                //             }
                //         }
                //     }
                //     post {
                //         cleanup {
                //             sh 'docker compose down -v'
                //         }
                //     }
                // }
                stage('Gateway Integration Tests') {
                    steps {
                        retry(2) {
                            echo 'Running gateway integration tests...'
                            sleep(10)
                            build job: 'graphql-gateway-integration-tests'
                        }
                    }
                }
            }
        }
        stage('E2E Tests') {
            when {
                allOf {
                    branch 'master'
                    expression { params.SKIP_E2E_TESTS == 'No' }
                }
            }
            steps {
                playwrightTests tags: "@audience-creation-page or @my-roster or @artist-page"
            }
        }
        stage('Validate Prod schema') {
            when {
                allOf {
                    branch 'master'
                    expression { params.DEPLOY_TO_PROD }
                    expression { params.VALIDATE_SCHEMA == true && isSchemaChanged() }
                }
            }
            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 {
        always {
            script {
                if (env.BRANCH_NAME == 'master') {
                    slackNotify channel: SLACK_BUILDS_CHANNEL
                }
            }
        }
        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()
        }
    }
}
