def APP_NAME = 'frontend-feature-fm'
def POEDITOR_PROJECT_ID = '226899'

pipeline {
    agent {
        label 'aws'
    }

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

    parameters {
        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('Unit Tests and Style Checks') {
            when {
                not {
                    anyOf {
                        expression { env.GITHUB_COMMENT ==~ /.*deploy pri.*/ }
                        expression { env.GITHUB_COMMENT ==~ /.*run e2e tests.*/ }
                    }
                }
            }
            steps {
                withCredentials([
                    string(credentialsId: 'packagecloud_read_token', variable: 'PACKAGECLOUD_TOKEN'),
                ]) {
                    yarnRun([
                        scriptNames: ['test'],
                        envVars: [
                            PACKAGECLOUD_TOKEN: "\${PACKAGECLOUD_TOKEN}"
                        ]
                    ])
                }
            }
        }
        stage('Static Application Security Tests') {
            when {
                not {
                    anyOf {
                        expression { env.GITHUB_COMMENT ==~ /.*deploy pri.*/ }
                        expression { env.GITHUB_COMMENT ==~ /.*run e2e tests.*/ }
                    }
                }
            }
            steps {
                sastTests(v2: true)
            }
        }
        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 {
                expression { env.GITHUB_COMMENT ==~ /.*deploy pri.*/ }
            }
            steps {
                withCredentials([
                    string(credentialsId: 'packagecloud_read_token', variable: 'PACKAGECLOUD_TOKEN')
                ]) {
                    script {
                        def priId = env.CHANGE_ID
                        def priDomain = "featurefm-${priId}.pullrequests.qaorch.com"

                        nodeSh(
                            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',
                                PACKAGECLOUD_TOKEN: "\${PACKAGECLOUD_TOKEN}",
                            ],
                            script: """
                                set -ex
                                yarn install --frozen-lockfile
                                yarn deploy:pri
                                node ./scripts/buildPrInstance.mjs
                            """
                        )

                        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 {
                expression { env.GITHUB_COMMENT ==~ /.*run e2e tests.*/ }
            }
            steps {
                playwrightTests(
                    tags: '@frontend_feature_fm',
                    envVars: [
                        BASE_URL_OVERRIDE_WORKSTATION: "https://featurefm-${env.CHANGE_ID}.pullrequests.qaorch.com",
                        USE_DYNAMIC_THROTTLING: 'true'
                    ],
                    reportSuffix: 'QA-frontend_feature_fm',
                    githubPRRepo: APP_NAME
                )
            }
        }
        stage('Deploy to QA') {
            when {
                branch 'master'
            }
            steps {
                withCredentials([
                    string(credentialsId: 'packagecloud_read_token', variable: 'PACKAGECLOUD_TOKEN'),
                ]) {
                    suiteAppBuild (
                        env: 'qa',
                        envVars: [
                            PACKAGECLOUD_TOKEN: "\${PACKAGECLOUD_TOKEN}",
                            POEDITOR_PROJECT_ID: POEDITOR_PROJECT_ID,
                        ]
                    )
                }

                suiteAppPublish (
                    env: "qa",
                    appName: APP_NAME
                )
            }
        }
        stage('Invalidate QA CDN') {
            when {
                branch 'master'
            }
            steps {
                cdnInvalidate(
                    env: 'qa',
                    appName: APP_NAME
                )
            }
        }
        stage('E2E Tests') {
            when {
                branch 'master'
            }
            steps {
                playwrightTests tags: '@frontend_feature_fm'
            }
        }
        stage('Deploy to Prod') {
            when {
                allOf {
                    branch 'master'
                    expression { params.DEPLOY_TO_PROD == 'Yes' }
                }
            }
            steps {
                withCredentials([
                    string(credentialsId: 'packagecloud_read_token', variable: 'PACKAGECLOUD_TOKEN'),
                ]) {
                    suiteAppBuild (
                        env: 'prod',
                        envVars: [
                            PACKAGECLOUD_TOKEN: "\${PACKAGECLOUD_TOKEN}",
                            POEDITOR_PROJECT_ID: POEDITOR_PROJECT_ID,
                        ]
                    )
                }

                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
                )
            }
        }
    }
}
