String GITHUB_REPOSITORY = 'python-neo4j-cypher-scheduler'
List<String> AWS_REGIONS = ['us-east-1']
String ECR_ACCOUNT_ID = '086679231553'
String PROD_ACCOUNT_ID = '437795906767'
String PROD_DEPLOYMENT_ROLE = 'prod-jenkins-aws-pipeline-agent'
String ECR_IMAGE_NAME = 'python-neo4j-cypher-scheduler'
String SLACK_NOTIFICATIONS_CHANNEL = '#neo4j-db'
String SESSION_NAME = "neo4j-cypher-scheduler"
String DEPLOY_ROLE = "qa-neo4j-cypher-scheduler-deploy-role"


/**
 * Use deployType depending on the service configuration on each environment.
 * if the service has enabled a cloudwatch_event to trigger on a schedule, set to UPDATE_CLOUDWATCH_EVENT
 */
QA_SERVICES = [
    'neo4j-cypher-assert-data-quality': [deployType: 'CREATE_TASK_DEFINITION'],
    'neo4j-cypher-augment': [deployType: 'CREATE_TASK_DEFINITION'],
    'neo4j-cypher-delete-liquigraphlock': [deployType: 'CREATE_TASK_DEFINITION'],
    'neo4j-cypher-housekeeping': [deployType: 'CREATE_TASK_DEFINITION'],
    'neo4j-cypher-qa-refresh': [deployType: 'CREATE_TASK_DEFINITION']
]

PROD_SERVICES = [
    'neo4j-cypher-assert-data-quality': [deployType: 'UPDATE_CLOUDWATCH_EVENT'],
    'neo4j-cypher-assert-snowflake-sync': [deployType: 'UPDATE_CLOUDWATCH_EVENT'],
    'neo4j-cypher-augment': [deployType: 'UPDATE_CLOUDWATCH_EVENT'],
    'neo4j-cypher-delete-liquigraphlock': [deployType: 'CREATE_TASK_DEFINITION'],
    'neo4j-cypher-housekeeping': [deployType: 'UPDATE_CLOUDWATCH_EVENT'],
]

pipeline {
    agent any

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

    parameters {
        booleanParam(name: 'DEPLOY_TO_PROD', defaultValue: true, 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, Git revision or PR ref (e.g. pull/PR_NUMBER/merge).')
    }

    triggers {
        issueCommentTrigger('.*retest this please.*')
    }

    stages {
        stage('Load Shared Libraries') {
            steps {
                library "jenkins-global-libraries@${params.SHARED_LIBRARIES_VERSION}"
            }
        }
        stage('Compliance Checks') {
            steps {
                complianceChecks()
            }
        }
        stage('Validate Software Catalog Definitions') {
            steps {
                script {
                    parallel(PROD_SERVICES.collectEntries {service, config ->
                        return [
                            (service): {
                                echo "Validating Software Catalog definition for ${service}"
                                datadogSoftwareCatalogValidate(serviceDefinitionFilePath: "software_catalog/${service}.yaml")
                            }
                        ]
                    })
                }
            }
        }
        stage('Unit Tests and Style Checks') {
            steps {
                withEcr {
                    withAWS(role: DEPLOY_ROLE, roleAccount: PROD_ACCOUNT_ID, roleSessionName: SESSION_NAME, useNode: true) {
                        println "IAM role name provided - using \"${DEPLOY_ROLE}\" as deployment role"
                        sh 'make lint-and-test'
                    }
                }
            }
        }
        stage('Static Application Security Tests') {
            steps {
                sastTests()
            }
        }
        stage('Sonar Scan and Analysis') {
            when {
                branch 'master'
            }
            steps {
                sonarScan project: GITHUB_REPOSITORY, language: 'py'
            }
        }
        stage('Create a Release') {
            when {
                anyOf {
                    branch 'master'
                    expression { env.GITHUB_COMMENT =~ 'build docker' }
                }
            }
            steps {
                dockerToEcr awsRegions: AWS_REGIONS, ecrAccountId: ECR_ACCOUNT_ID, imageName: ECR_IMAGE_NAME, imageTag: env.GIT_COMMIT
            }
        }
        stage('Deploy to QA') {
            when {
                branch 'master'
            }
            steps {
                script {
                    parallel(QA_SERVICES.collectEntries {service, config ->
                        return [
                            (service): {
                                def deploymentType = config.get('deployType', 'CREATE_TASK_DEFINITION')

                                fargateDeploy environment: 'qa', awsRegions: AWS_REGIONS, gitCommit: env.GIT_COMMIT,
                                    imageNameOverride: ECR_IMAGE_NAME,
                                    serviceName: service,
                                    ecrRegistryAccountId: ECR_ACCOUNT_ID,
                                    awsDeploymentTargetAccountId: PROD_ACCOUNT_ID,
                                    awsDeploymentRoleName: PROD_DEPLOYMENT_ROLE,
                                    deployType: deploymentType
                            }
                        ]
                    })
                }
            }
        }
        stage('Scan Docker Image') {
            when {
                anyOf {
                    branch 'master'
                    expression { env.GITHUB_COMMENT =~ 'build docker' }
                }
            }
            steps {
                dockerScan awsRegion: AWS_REGIONS[0],
                ecrAccountId: ECR_ACCOUNT_ID,
                imageName: ECR_IMAGE_NAME,
                imageTag: env.GIT_COMMIT,
                vulnerabilitiesToIgnore: [
                            /**
                            * vulnerability is for redis server 7.0.10, but being flagged for installing python library
                            */
                            'CVE-2023-31484',
                            'CVE-2025-66418',
                            'CVE-2025-66471',
                           ]
            }
        }
        stage('Deploy to Prod') {
            when {
                allOf {
                    branch 'master'
                    expression { params.DEPLOY_TO_PROD }
                }
            }
            parallel {
                stage('Deploy to Prod') {
                    steps {
                        script {
                            parallel(PROD_SERVICES.collectEntries {service, config ->
                                return [
                                    (service): {
                                        def deploymentType = config.get('deployType', 'CREATE_TASK_DEFINITION')

                                        fargateDeploy environment: 'prod', awsRegions: AWS_REGIONS, gitCommit: env.GIT_COMMIT,
                                            imageNameOverride: ECR_IMAGE_NAME,
                                            serviceName: service,
                                            ecrRegistryAccountId: ECR_ACCOUNT_ID,
                                            awsDeploymentTargetAccountId: PROD_ACCOUNT_ID,
                                            awsDeploymentRoleName: PROD_DEPLOYMENT_ROLE,
                                            deployType: deploymentType
                                        
                                        datadogSoftwareCatalogPublish(serviceDefinitionFilePath: "software_catalog/${service}.yaml")
                                    }
                                ]
                            })
                        }
                    }
                }
            }
        }
    }
    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
                }
            }
        }
        cleanup {
            cleanWs()
        }
    }
}
