import groovy.transform.Field

@Field def GITHUB_REPOSITORY = 'google-tag-manager-wrapper'

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_REPO_NAME = "google-tag-manager-wrapper"

List<String> VULNERABILITIES_TO_IGNORE = [
    "CVE-2025-64756",
]

PROD_SERVICES = [
        [serviceName: 'gtm-tiktok', prodClusterName: 'prod-gtm-tiktok', awsDeploymentRoleName: 'prod-jenkins-aws-pipeline-agent', awsDeploymentTargetAccountId: '437795906767'],
        [serviceName: 'gtm-tiktok-preview', prodClusterName: 'prod-gtm-tiktok', awsDeploymentRoleName: 'prod-jenkins-aws-pipeline-agent', awsDeploymentTargetAccountId: '437795906767'],
        [serviceName: 'gtm-songwhip', prodClusterName: 'prod-gtm-songwhip', awsDeploymentRoleName: 'prod-jenkins-aws-pipeline-agent', awsDeploymentTargetAccountId: '437795906767'],
        [serviceName: 'gtm-songwhip-preview', prodClusterName: 'prod-gtm-songwhip', awsDeploymentRoleName: 'prod-jenkins-aws-pipeline-agent', awsDeploymentTargetAccountId: '437795906767'],
        [serviceName: 'gtm-sonymusicfans', prodClusterName: 'prod-gtm-sonymusicfans', awsDeploymentRoleName: 'prod-jenkins-aws-pipeline-agent', awsDeploymentTargetAccountId: '437795906767'],
        [serviceName: 'gtm-sonymusicfans-preview', prodClusterName: 'prod-gtm-sonymusicfans', awsDeploymentRoleName: 'prod-jenkins-aws-pipeline-agent', awsDeploymentTargetAccountId: '437795906767']
]

pipeline {
    agent any

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

    parameters {
        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.')
        choice(name: 'SERVICE_CHOICE', choices: ['all','prod-gtm-tiktok','prod-gtm-songwhip','prod-gtm-sonymusicfans'], description: 'Update either all google tag manager services or a specific one.')
    }

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

    stages {
        stage('Load Shared Libraries') {
            steps {
                library "jenkins-global-libraries@${params.SHARED_LIBRARIES_VERSION}"
            }
        }
        stage('Validate Software Catalog Definitions') {
            steps {
                script {
                    parallel(PROD_SERVICES.collectEntries { service ->
                        return [
                            (service.serviceName): {
                                echo "Validating Software Catalog definition for ${service.serviceName}"
                                datadogSoftwareCatalogValidate(
                                    serviceDefinitionFilePath: "software_catalog/${service.serviceName}.yaml",
                                )
                            }
                        ]
                    })
                }
            }
        }
        stage('Create a Release') {
            when {
                anyOf {
                    branch 'master'
                    expression { env.GITHUB_COMMENT =~ 'build docker' }
                }
            }
            steps {
                dockerToEcr awsRegions: AWS_REGIONS, ecrAccountId: ECR_ACCOUNT_ID, imageName: GITHUB_REPOSITORY, imageTag: env.GIT_COMMIT,
                    dockerBuildTarget: 'deploy'
            }
        }
        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: GITHUB_REPOSITORY, imageTag: env.GIT_COMMIT,
                    vulnerabilitiesToIgnore: VULNERABILITIES_TO_IGNORE
            }
        }
        stage('Deployment') {
            when {
                allOf {
                    branch 'master'
                    expression { return params.SERVICE_CHOICE in ['all','prod-gtm-songwhip'] }
                }
            }
            steps {
                script {
                    parallel(PROD_SERVICES.collectEntries { service ->
                        [
                                (service.serviceName) : {
                                    fargateDeploy environment: 'prod', awsRegions: AWS_REGIONS, gitCommit: env.GIT_COMMIT,
                                    serviceName: service.serviceName,
                                    clusterName: service.prodClusterName,
                                    ecrRegistryAccountId: ECR_ACCOUNT_ID,
                                    imageNameOverride: ECR_REPO_NAME,
                                    awsDeploymentTargetAccountId: service.awsDeploymentTargetAccountId,
                                    awsDeploymentRoleName: service.awsDeploymentRoleName
                                }]
                    })
                }
            }
        }
        stage('Publish Software Catalog Definition') {
            when {
                allOf {
                    branch 'master'
                    expression { return params.SERVICE_CHOICE in ['all','prod-gtm-songwhip'] }
                }
            }
            steps {
                script {
                    parallel(PROD_SERVICES.collectEntries { service ->
                        return [
                            (service.serviceName): {
                                echo "Publishing Software Catalog definition for ${service.serviceName}"
                                datadogSoftwareCatalogPublish(
                                    serviceDefinitionFilePath: "software_catalog/${service.serviceName}.yaml",
                                )
                            }
                        ]
                    })
                }
            }
        }
    }

    post {
        cleanup {
            cleanWs()
        }
    }
}
