String QA_TARGET_ENVIRONMENT = 'qa'

pipeline {
    agent any
    parameters {
        choice(
            choices: ['dev' , 'qa'],
            description: 'Neo4j cluster to refresh',
            name: 'Environment')
    }

    stages {
        stage('Notify Slack') {
            steps {
                slackSend channel: "#neo4j-db", message: "Build started for ${env.JOB_NAME} in ${params.Environment}: ${env.BUILD_URL}"
            }
        }
        stage('Refresh Neo4j') {
            steps {
                build job: 'python-neo4j-utils-restore-cluster', parameters:
                    [
                        string(name: 'Environment', value: params.Environment),
                        string(name: 'NEO4J_RESTORE_BACKUP_DATE', value: params.NEO4J_RESTORE_BACKUP_DATE)
                    ]
            }
        }
        stage('Post-Refresh Cypher Queries') {
            steps {
                build job: 'neo4j-cypher-scheduler-refresh-query-runner', parameters:
                    [[$class: 'StringParameterValue', name: 'Environment', value: params.Environment]]
            }
        }
        stage ('Clear qa-graphql-user redis cache') {
            when {
                // Only clear redis cache for qa-graphql-user
                expression { params.Environment == 'qa' }
            }
            steps {
                build job: 'qa-graphql-user-redis-clear-cache'
            }
        }
    }
    post {
       failure {
           slackSend channel: "#neo4j-db", color: "danger", message: "Build finished for ${env.JOB_NAME} in ${params.Environment}: ${env.BUILD_URL}"
       }
       success {
           slackSend channel: "#neo4j-db", color: "good", message: "Build finished for ${env.JOB_NAME} in ${params.Environment}: ${env.BUILD_URL}"
           
           script {
               if (params.Environment == 'qa') {
                   build job: 'rds-refresh-pipeline', wait: false, parameters: [
                       string(name: 'SERVICE_NAME', value: 'neighbouring-rights-delivery'),
                       string(name: 'TARGET_ENVIRONMENT', value: QA_TARGET_ENVIRONMENT)
                   ]
                   build job: 'rds-refresh-pipeline', wait: false, parameters: [
                       string(name: 'SERVICE_NAME', value: 'neighbouring-rights-ownership-delivery'),
                       string(name: 'TARGET_ENVIRONMENT', value: QA_TARGET_ENVIRONMENT)
                   ]
                   build job: 'nr-s3-cleanup-utils', wait: false
                   build job: 'rds-refresh-pipeline', wait: false, parameters: [
                       string(name: 'SERVICE_NAME', value: 'publishing-compositions'),
                       string(name: 'TARGET_ENVIRONMENT', value: QA_TARGET_ENVIRONMENT)
                   ]
                   build job: 'publishing-qa-s3-bucket-cleanup', wait: false
               }
           }
       }
    }

}
