def GITHUB_REPOSITORY = 'songwhip-api'
def SLACK_E2E_NOTIFY_CHANNEL = '#songwhip-alerts-dev'
def SLACK_NOTIFICATION_CHANNEL = "#songwhip-alerts-dev"
def AWS_REGIONS = ['us-east-1']
def ECR_ACCOUNT_ID = '086679231553'
def QA_ACCOUNT_ID = '619719722105'
def PROD_ACCOUNT_ID = '926734670777'
def QA_DEPLOYMENT_ROLE = 'qa-songwhip-jenkins-pipeline-deploy-role'
def PROD_DEPLOYMENT_ROLE = 'prod-songwhip-jenkins-pipeline-deploy-role'

def VULNERABILITIES_TO_IGNORE = [
    "CVE-2026-2673",  // remove when fixed in alpine image
    "CVE-2026-28388", // remove when fixed in node:24-alpine base image
    "CVE-2026-28389", // remove when fixed in node:24-alpine base image
    "CVE-2026-28390", // remove when fixed in node:24-alpine base image
    "CVE-2026-31790", // remove when fixed in node:24-alpine base image
    "CVE-2026-31789", // remove when fixed in node:24-alpine base image
    "CVE-2026-28387", // remove when fixed in node:24-alpine base image
    "CVE-2026-34182", // node 24.16.0 has it, but we need to downgrade
]

pipeline {
    agent {
        label 'aws'
    }

    parameters {
        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('Tests & Analysis') {
            parallel {
                stage('Static Application Security Tests') {
                    steps {
                        sastTests()
                    }
                }
                stage('Datadog Software Catalog Validation') {
                    steps {
                        script {
                            datadogSoftwareCatalogValidate()
                        }
                    }
                }
                stage('Format, Lint & Unit Tests') {
                    steps {
                        pnpmRun(scriptNames: ['test'])
                    }
                }
                stage('Integration Tests') {
                    steps {
                        build(
                            job: 'qa-songwhip-api-integration-tests',
                            parameters: [
                                string(name: 'GIT_COMMIT', value: env.GIT_COMMIT)
                            ]
                        )
                    }
                }
            }
        }

        stage('Create Docker Image') {
            when {
                branch 'master'
            }
            steps {
                withCredentials([
                    string(credentialsId: 'github_packages_token', variable: 'GITHUB_NPM_TOKEN'),
                    string(credentialsId: 'poeditor-api-token', variable: 'POEDITOR_API_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'],
                            [id: 'POEDITOR_API_TOKEN', env: 'POEDITOR_API_TOKEN'],
                        ]
                    )
                }
            }
        }

        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,
                    failBuild: true,
                    slackNotificationChannel: SLACK_NOTIFICATION_CHANNEL
                )
            }
        }

        stage('Apply QA Schema Migrations') {
            when {
                branch 'master'
            }
            steps {
                build(
                    job: 'qa-songwhip-api-run-schema-migrations',
                    parameters: [
                        string(name: 'GIT_COMMIT', value: env.GIT_COMMIT),
                        string(name: 'ECR_ACCOUNT_ID', value: ECR_ACCOUNT_ID)
                    ]
                )
            }
        }

        stage('Deploy 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('E2E Tests') {
            when {
                allOf {
                    branch 'master'
                    expression { params.SKIP_E2E_TESTS == 'No' }
                }
            }
            steps {
                playwrightTests tags: "@songwhip_app", reportSuffix: "Staging-E2E"
            }
            post {
                regression {
                    slackNotify channel: SLACK_E2E_NOTIFY_CHANNEL
                }
                fixed {
                    slackNotify channel: SLACK_E2E_NOTIFY_CHANNEL
                }
            }
        }

        stage('Apply PROD Schema Migrations') {
            when {
                branch 'master'
            }
            steps {
                build(
                    job: 'prod-songwhip-api-run-schema-migrations',
                    parameters: [
                        string(name: 'GIT_COMMIT', value: env.GIT_COMMIT),
                        string(name: 'ECR_ACCOUNT_ID', value: ECR_ACCOUNT_ID)
                    ]
                )
            }
        }

        stage('Deploy to PROD') {
            when {
                branch 'master'
            }
            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
                )
            }
        }

        stage('Datadog Software Catalog Publish') {
            when {
                branch 'master'
            }
            steps {
                script {
                    datadogSoftwareCatalogPublish()
                }
            }
        }
    }

    post {
        failure {
            cleanWs()
            echo "Pipeline failed for commit: ${env.GIT_COMMIT}. Workspace cleaned."
        }
    }
}
