String AWS_REGION = 'us-east-1'
String AWS_ACCOUNT_ID = '437795906767'
String SLACK_NOTIFICATIONS_CHANNEL = '#security-team'
String QA_INVOKE_ROLE = 'qa-populate-hfa-pending-request-lambda-invoke-role'
String PROD_INVOKE_ROLE = 'prod-populate-hfa-pending-request-lambda-invoke-role'
String SESSION_NAME = 'jenkins-lambda-invoke'

pipeline {
    agent any

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

    parameters {
        choice(name: 'ENV', choices: ['qa', 'prod'], description: 'Target environment')
        string(name: 'DATETIME', defaultValue: '', description: 'Datetime (e.g., 2025-05-01 13:30:00)')
    }

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

        stage('Invoke Lambda via Docker') {
            steps {
                script {
                    def selectedRole = (params.ENV == 'qa') ? QA_INVOKE_ROLE : PROD_INVOKE_ROLE
                    withAWS(role: selectedRole, roleAccount: AWS_ACCOUNT_ID, roleSessionName: SESSION_NAME, useNode: true) {
                        dir('scripts/invoke-populate-hfa-pending-request-lambda') {
                            sh """
                                docker compose build
                                docker compose run --rm lambda-invoker ${params.ENV} "${params.DATETIME}"
                            """
                        }
                    }
                }
            }
        }
    }
    post {
        success {
            script {
                if (params.ENV == 'prod') {
                    slackNotify channel: SLACK_NOTIFICATIONS_CHANNEL
                }
            }
        }
        failure {
            script {
                if (params.ENV == 'prod') {
                    slackNotify channel: SLACK_NOTIFICATIONS_CHANNEL
                }
            }
        }
        cleanup {
            cleanWs()
        }
    }
}
