String GITHUB_REPOSITORY = 'martech-snowflake-salesforce-node'
String SERVICE_NAME = 'snowflake-salesforce-node'
String ECR_ACCOUNT_ID = '086679231553'
List<String> AWS_REGIONS = ['us-east-1']
String SLACK_NOTIFICATIONS_CHANNEL = '#martech-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'

List<String> VULNERABILITIES_TO_IGNORE = []

pipeline {
    agent any

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

    parameters {
        booleanParam(name: 'DEPLOY_TO_PROD', defaultValue: false, 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('Checkout') {
            steps {
                script {
                    cleanWs()
                    def scmVars = checkout scm
                    // Set SCM vars as environment variables to replicate default checkout functionality
                    scmVars.each { k, v ->
                        env."${k}" = v
                    }
                }
            }
        }
        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: 'js', exclusions: 'e2e/** , lib/test-helpers/**, **/test/**'
                    }
                }
                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
                                '''
                            }
                        }
                    }
                }
            }
        }
        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: SERVICE_NAME,
                    imageNameOverride: 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') {
            when {
                branch 'master'
            }
            parallel {
                stage('Service Integration Tests') {
                    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
                                    '''
                                }
                            }
                        }
                    }
                }
            }
        }
        stage('E2E Tests') {
            when {
                branch 'master'
            }
            environment {
                MAKE_TARGET = "cypress_run_${GITHUB_REPOSITORY.replaceAll('-', '_')}"
            }
            steps {
                e2eTests makeTarget: env.MAKE_TARGET
            }
            post {
                regression {
                    slackNotify channel: '#cypress-test-e2e-results'
                }
                fixed {
                    slackNotify channel: '#cypress-test-e2e-results'
                }
            }
        }*/
        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: SERVICE_NAME,
                    imageNameOverride: 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
                }
            }
        }
    }
}
