def APP_NAME = 'frontend-distribution'
def SLACK_NOTIFY_CHANNEL = '#content-creation-mgmt-alerts'
def DEFAULT_AWS_REGION = 'us-east-1'
def POEDITOR_PROJECT_ID = '67505'
def QA_AUTH0_CLIENT_ID='UwAkQHgn1qszdr59k2A3kn8FuYITQ373'

def QA_CDN_URL = 'https://qa-cdn.theorchard.io'
def PROD_CDN_URL = 'https://cdn.theorchard.io'
def QA_API_URL = 'https://qa-ows-grass.theorchard.io'
def PROD_API_URL = 'https://ows-grass.theorchard.io'

pipeline {
    agent {
        label 'aws'
    }

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

    parameters {
        choice(name: 'MINIFY', choices: [1, 0], description: 'Whether or not to minify.')
        choice(name: 'DEPLOY_TO_PROD', choices: ['Yes', 'No'], 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.*|.*deploy pri.*|.*run e2e tests.*')
    }

    stages {
        stage('Load Shared Libraries') {
            steps {
                library "jenkins-global-libraries@${params.SHARED_LIBRARIES_VERSION}"
            }
        }
        stage('Compliance Checks') {
            steps {
                complianceChecks()
            }
        }
        stage('Validate Software Catalog Definition') {
            steps {
                datadogSoftwareCatalogValidate()
            }
        }
        stage('Unit Tests and Style Checks') {
            when {
                not {
                    environment name: 'GITHUB_COMMENT', value: 'deploy pri'
                }
            }
            steps {
                withCredentials([
                    string(credentialsId: 'packagecloud_read_token', variable: 'PACKAGECLOUD_TOKEN'),
                ]) {
                    pnpmRun(
                        scriptNames: ['test'],
                        envVars: [
                            PACKAGECLOUD_TOKEN: "\${PACKAGECLOUD_TOKEN}"
                        ]
                    )
                }
            }
        }
        stage('Static Application Security Tests') {
            when {
                not {
                    anyOf {
                        environment name: 'GITHUB_COMMENT', value: 'run e2e tests'
                        environment name: 'GITHUB_COMMENT', value: 'deploy pri'
                    }
                }
            }
            steps {
                sastTests()
            }
        }
        stage('Sonar Scan and Analysis') {
            when {
                branch 'master'
            }
            steps {
                script {
                    echo "Running Sonar scan for ${APP_NAME}"
                    sonarScan project: APP_NAME, language: 'js'
                }
            }
        }
        stage('Deploy to PR Instance') {
            when {
                environment name: 'GITHUB_COMMENT', value: 'deploy pri'
            }
            steps {
                withCredentials([
                    string(credentialsId: 'packagecloud_read_token', variable: 'PACKAGECLOUD_TOKEN'),
                    string(credentialsId: 'poeditor-api-token', variable: 'POEDITOR_API_TOKEN')
                ]) {
                    script {
                        def priId = env.CHANGE_ID
                        def priDomain = "distro-${priId}.pullrequests.qaorch.com"

                        nodeSh(
                            user: 'root',
                            envVars: [
                                ENV: 'qa',
                                PRI_ID: priId,
                                CDN_URL: 'https://qa-cdn.theorchard.io',
                                API_URL: 'https://grassproxy.pullrequests.qaorch.com',
                                GRAPHQL_URL: 'https://grassproxy.pullrequests.qaorch.com/graphql-gateway/graphql',
                                AUTH0_DOMAIN: 'qalogin.theorchard.com',
                                AUTH0_CLIENT_ID: 'UwAkQHgn1qszdr59k2A3kn8FuYITQ373',
                                AUTH0_AUDIENCE: 'https://workstation.qaorch.com/api',
                                AUTH0_REDIRECT: "https://pullrequests.qaorch.com/auth0Redirect?to=${priDomain}",
                                AUTH0_ORG_ID_ORCHARD: 'org_vdEfyCAGWYnTkX6G',
                                AUTH0_ORG_ID_AWAL: 'org_ZowffAYGJyqvOeIJ',
                                GRASS_SESSION_TOKEN_START_ENDPOINT: 'https://workstation.qaorch.com/login/startsession',
                                GRASS_SESSION_TOKEN_CLEAR_ENDPOINT: 'https://workstation.qaorch.com/logout/clearsession',
                                POEDITOR_PROJECT_ID: POEDITOR_PROJECT_ID,
                                POEDITOR_API_TOKEN: "\${POEDITOR_API_TOKEN}",
                                PACKAGECLOUD_TOKEN: "\${PACKAGECLOUD_TOKEN}",
                            ],
                            script: """
                                set -ex
                                corepack enable pnpm
                                pnpm install --frozen-lockfile
                                pnpm run deploy:pri
                            """
                        )

                        suiteAppPublish(
                            env: 'qa',
                            appName: APP_NAME,
                            subpath: "prs/${priId}"
                        )

                        githubPostPrComment(
                            repo: APP_NAME,
                            message: "PR-Instance deployed to: https://${priDomain}"
                        )
                    }
                }
            }
        }
        stage('E2E Tests on PR Instance') {
            when {
                environment name: 'GITHUB_COMMENT', value: 'run e2e tests'
            }
            steps {
                playwrightTests(
                    tags: "@frontend_distribution",
                    envVars: [
                        BASE_URL_OVERRIDE_WORKSTATION: "https://distro-${env.CHANGE_ID}.pullrequests.qaorch.com",
                        USE_DYNAMIC_THROTTLING: 'true'
                    ],
                    reportSuffix: "QA-frontend_distribution",
                    githubPRRepo: APP_NAME
                )
            }
        }
        stage('Deploy to QA') {
            when {
                branch 'master'
            }
            steps {
                // Build
                withCredentials([
                    string(credentialsId: 'packagecloud_read_token', variable: 'PACKAGECLOUD_TOKEN')
                ]) {
                    suiteAppBuild (
                        env: 'qa',
                        scriptNames: ['deploy:app'],
                        detectPackageManager: true,
                        envVars: [
                            PACKAGECLOUD_TOKEN: "\${PACKAGECLOUD_TOKEN}",
                            POEDITOR_PROJECT_ID: POEDITOR_PROJECT_ID,
                            CDN_URL: QA_CDN_URL,
                            API_URL: QA_API_URL
                        ]
                    )

                    suiteAppPublish (
                        env: "qa",
                        appName: APP_NAME
                    )
                }
            }
        }
        stage('Invalidate QA CDN') {
            when {
                branch 'master'
            }
            steps {
                cdnInvalidate(
                    env: 'qa',
                    appName: APP_NAME
                )
            }
        }
        stage('E2E Tests on QA') {
            when {
                branch 'master'
            }
            steps {
                playwrightTests tags: '@frontend_distribution', envVars: ['USE_DYNAMIC_THROTTLING': 'true']
            }
        }
        stage('Deploy to Prod') {
            when {
                allOf {
                    branch 'master'
                    expression { params.DEPLOY_TO_PROD == 'Yes' }
                }
            }
            steps {
                // Build
                withCredentials([
                    string(credentialsId: 'packagecloud_read_token', variable: 'PACKAGECLOUD_TOKEN')
                ]) {
                    suiteAppBuild (
                        env: 'prod',
                        scriptNames: ['deploy:app'],
                        detectPackageManager: true,
                        envVars: [
                            PACKAGECLOUD_TOKEN: "\${PACKAGECLOUD_TOKEN}",
                            POEDITOR_PROJECT_ID: POEDITOR_PROJECT_ID,
                            CDN_URL: PROD_CDN_URL,
                            API_URL: PROD_API_URL
                        ]
                    )

                    suiteAppPublish (
                        env: "prod",
                        appName: APP_NAME
                    )
                }
            }
        }
        stage('Invalidate Prod CDN') {
            when {
                allOf {
                    branch 'master'
                    expression { params.DEPLOY_TO_PROD == 'Yes' }
                }
            }
            steps {
                cdnInvalidate(
                    env: 'prod',
                    appName: APP_NAME
                )
            }
        }
        stage('Publish Software Catalog') {
            when {
                allOf {
                    branch 'master'
                    expression { params.DEPLOY_TO_PROD == 'Yes' }
                }
            }
            steps {
                datadogSoftwareCatalogPublish()
            }
        }

    }
    post {
        cleanup {
            cleanWs()
        }
    }
}
