String SLACK_NOTIFICATIONS_CHANNEL = '#security-team'
String PROD_ACCOUNT_ID = '437795906767'
String ASSUME_ROLE = 'prod-splitio-ff-manager-secrets-assume-role'
def TEAMS_CHOICES = ['-- Select a team --'] + getDatadogTeamsList()


pipeline {
    agent any

    environment {
        SPLITIO_WORKSPACE_ID = '5b5212f0-21c9-11ea-a4e7-0a9b522eabbd'
        HARNESS_ACCOUNT_IDENTIFIER = 'cej_iP27SSSgxFiM6TOjAw'
    }

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

    parameters {
        choice(
            name: 'OUTPUT_TYPE', 
            choices: ['excel', 'json', 'table'], 
            description: 'Required. Output format for the feature flag audit.'
        )
        choice(
            name: 'FILTER_TEAM',
            choices: TEAMS_CHOICES,
            description: 'Optional. Filter audit results by team. Leave "-- Select a team --" for no filtering.'
        )
    }

    stages {
        stage('Load Shared Libraries') {
            steps {
                library "jenkins-global-libraries@master"
            }
        }

        stage('Audit Feature Flags') {
            steps {
                script {
                    def args = "audit --output \"${params.OUTPUT_TYPE}\""

                    if (params.FILTER_TEAM && params.FILTER_TEAM != '-- Select a team --') {
                        args += " --filter-team \"${params.FILTER_TEAM}\""
                    }

                    echo "Final CLI Command: feature-flag-tool ${args}"

                    withSecrets(awsAccountId: PROD_ACCOUNT_ID, awsRole: ASSUME_ROLE, secrets: [
                        [id: 'prod/splitio-ff-manager/SPLITIO_ADMIN_API_KEY', environmentVariable: 'HARNESS_API_KEY']
                    ]) {
                        dir('splitio_ff_manager') {
                            withEcr {
                                sh """
                                    docker compose run --rm --build \
                                    -e HARNESS_ACCOUNT_IDENTIFIER \
                                    -e SPLITIO_WORKSPACE_ID \
                                    -e HARNESS_API_KEY \
                                    feature-flag-tool ${args}
                                """
                            }
                        }
                    }
                }
            }
            post {
                success {
                    script {
                        def outputFile
                        if (params.OUTPUT_TYPE == 'excel') {
                            outputFile = "splitio_ff_manager/artifacts/feature_flags_audit.xlsx"
                        } else if (params.OUTPUT_TYPE == 'json') {
                            outputFile = "splitio_ff_manager/artifacts/feature_flags_audit.json"
                        } else {
                            outputFile = null
                        }

                        if (outputFile) {
                            archiveArtifacts artifacts: outputFile, followSymlinks: true
                            echo "Archived audit output: ${outputFile}"
                        } else {
                            echo "No artifacts to archive for table output."
                        }
                    }
                }
            }
        }
    }

    post {
        regression {
            script {
                slackNotify channel: SLACK_NOTIFICATIONS_CHANNEL
            }
        }
        fixed {
            script {
                slackNotify channel: SLACK_NOTIFICATIONS_CHANNEL
            }
        }
        cleanup {
            cleanWs()
        }
    }
}

def getDatadogTeamsList() {
    node {
        script {
            library "jenkins-global-libraries@master"
        }
        withSecrets(awsAccountId: '437795906767', awsRole: 'prod-splitio-ff-manager-secrets-assume-role', secrets: [
            [id: 'prod/splitio-ff-manager/DD_API_KEY', environmentVariable: 'DD_API_KEY'],
            [id: 'prod/splitio-ff-manager/DD_APP_KEY', environmentVariable: 'DD_APP_KEY']
        ]) {
            echo "Fetching teams from Datadog..."
            def response = sh(
                returnStdout: true,
                script: """
                  curl -s -X GET "https://api.datadoghq.com/api/v2/team" \\
                    -H "Accept: application/json" \\
                    -H "DD-API-KEY: $DD_API_KEY" \\
                    -H "DD-APPLICATION-KEY: $DD_APP_KEY"
                """
            ).trim()

            def json = readJSON text: response
            def teams = json.data.collect { it.attributes.name }
            return teams.sort()
        }
    }
}
