String GITHUB_REPOSITORY = 'ows-notifications'
String ECR_ACCOUNT_ID = '086679231553'
List<String> AWS_REGIONS = ['us-east-1']
String SLACK_NOTIFICATIONS_CHANNEL = '#notifications'
String ACCOUNT_ID = '437795906767'
String DEPLOYMENT_ROLE = 'prod-jenkins-aws-pipeline-agent'
String INTEGRATION_TEST_ROLE = 'qa-ows-notifications-integration-test-role'
String SESSION_NAME = 'qa-ows-notifications-integration-test'


pipeline {
    agent {
        label 'aws'
    }

    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 or Git revision.')
    }

    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 Definition') {
            steps {
                datadogSoftwareCatalogValidate()
            }
        }
        stage('Tests') {
            parallel {
                stage('Unit Tests and Style Checks') {
                    steps {
                        withEcr {
                            script {
                                runDockerTests('unit-tests')
                            }
                        }
                    }
                    post {
                        success {
                            xunit tools: [JUnit(pattern: 'reports/pyunit.xml', deleteOutputFiles: true, failIfNotNew: true, stopProcessingIfError: true)]
                            recordCoverage(tools: [[parser: 'COBERTURA', pattern: 'reports/coverage.xml']], enabledForFailure: true, failOnError: true, sourceDirectories: [[path: "notifications"]])
                        }
                    }
                }
                stage('Neo4j Integration Tests') {
                    steps {
                        withEcr {
                            script {
                                runDockerTests('neo4j-integration-tests')
                            }
                        }
                    }
                }
                stage('Static Application Security Tests') {
                    steps {
                        sastTests()
                    }
                }
            }
        }
        stage('Sonar Scan and Analysis') {
            when {
               branch 'master'
            }
            steps {
               sonarScan project: GITHUB_REPOSITORY, language: 'py', exclusions: 'tests/**,templates/**'
            }
        }
        stage('Create a Release') {
            when {
                branch 'master'
            }
            steps {
                dockerToEcr awsRegions: AWS_REGIONS, ecrAccountId: ECR_ACCOUNT_ID, imageName: GITHUB_REPOSITORY,
                    imageTag: env.GIT_COMMIT, dockerBuildTarget: 'main'
            }
        }
        stage('Scan Docker Image') {
            when {
                branch 'master'
            }
            steps {
                dockerScan awsRegion: AWS_REGIONS[0], ecrAccountId: ECR_ACCOUNT_ID, imageName: GITHUB_REPOSITORY,
                 imageTag: env.GIT_COMMIT, failBuild: false
            }
        }
        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: ACCOUNT_ID, awsDeploymentRoleName: DEPLOYMENT_ROLE
            }
        }
        stage('Integration Tests') {
            when {
                branch 'master'
            }
            steps {
                withEcr {
                    withAWS(role: INTEGRATION_TEST_ROLE, roleAccount: ACCOUNT_ID, roleSessionName: SESSION_NAME, useNode: true) {
                        script {
                            runDockerTests('integration-tests')
                        }
                    }
                }
            }
        }
        stage('E2E Tests') {
            when {
                branch 'master'
            }
            environment {
                TAGS = "@${GITHUB_REPOSITORY.replaceAll('-', '_')}"
            }
            steps {
                playwrightTests tags: env.TAGS
            }
        }
        stage('Deploy to Prod') {
            when {
                allOf {
                    branch 'master'
                    expression { params.DEPLOY_TO_PROD }
                }
            }
            steps {
                fargateDeploy environment: 'prod', awsRegions: AWS_REGIONS, gitCommit: env.GIT_COMMIT,
                    serviceName: GITHUB_REPOSITORY, ecrRegistryAccountId: ECR_ACCOUNT_ID,
                    awsDeploymentTargetAccountId: ACCOUNT_ID, awsDeploymentRoleName: DEPLOYMENT_ROLE
                datadogSoftwareCatalogPublish()
            }
        }
    }

    post {
        always {
            script {
                if (env.BRANCH_NAME == 'master') {
                    slackNotify channel: SLACK_NOTIFICATIONS_CHANNEL
                }
            }
        }
        cleanup {
            cleanWs()
        }
    }
}

def runDockerTests(String profileName) {
    echo "Starting Docker Compose tests for profile: ${profileName}"
    def projectName = "${env.BUILD_TAG}-${profileName}".toLowerCase()

    try {
        sh """
            docker compose -p ${projectName} -f docker-compose-tests.yml \
                --profile ${profileName} up \
                --build \
                --force-recreate \
                --renew-anon-volumes \
                --abort-on-container-exit \
                --exit-code-from ${profileName} \
                --attach ${profileName} \
                --quiet-pull
        """
    } finally {
        echo "Cleaning up Docker resources for ${profileName}..."
        sh "docker compose -p ${projectName} -f docker-compose-tests.yml --profile ${profileName} down --rmi local --volumes --remove-orphans"
    }
}
