String AWS_ACCOUNT_ID = '437795906767'
String QA_S3_ASSUME_ROLE = 'qa-product-store-eligibility-check-s3-assume-role'
String PROD_S3_ASSUME_ROLE = 'prod-product-store-eligibility-check-s3-assume-role'
String SLACK_NOTIFICATIONS_CHANNEL = '#content-creation-mgmt-alerts'

pipeline {
    agent any

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

    parameters {
        choice(
            name: 'ENVIRONMENT',
            choices: ['prod', 'qa'],
            description: 'Environment to run the check against'
        )
        stashedFile(
            name: 'UPCS_FILE',
            description: 'Optional: Upload a UPC file (one UPC per line). Recommended if you need to process more than 7,000 UPCs.'
        )
        text(
            name: 'UPC_LIST',
            defaultValue: '',
            description: 'One UPC per line'
        )
        string(
            name: 'STORE_ID',
            defaultValue: '',
            description: 'Store ID'
        )
        choice(
            name: 'DELIVERY_TYPE',
            choices: ['complete_album', 'metadata_update'],
            description: 'Delivery type'
        )
    }

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

        stage('Run Product Store Eligibility Check') {
            steps {
                script {
                    env.CONCURRENCY = 100
                    env.TIMEOUT = 900
                    S3_ASSUME_ROLE = "${params.ENVIRONMENT == "prod" ? PROD_S3_ASSUME_ROLE : QA_S3_ASSUME_ROLE}"

                    def fileUploaded = false
                    def volumeArg = ''
                    def filePath = ''
                    withFileParameter(name: 'UPCS_FILE', allowNoFile: true) {
                        def status = sh(
                            script: '''
                                if [ -n "$UPCS_FILE" ] && [ -s "$UPCS_FILE" ]; then
                                    cp "$UPCS_FILE" "$WORKSPACE/upc_file.txt"
                                    exit 0
                                else
                                    exit 1
                                fi
                            ''',
                            returnStatus: true
                        )

                        if (status == 0 && fileExists("${env.WORKSPACE}/upc_file.txt")) {
                            fileUploaded = true
                            filePath = '/var/app/upc_file.txt'
                            volumeArg = "--volume ${env.WORKSPACE}/upc_file.txt:${filePath}"
                        }
                    }

                    if (!fileUploaded && !params.UPC_LIST?.trim()) {
                        error "You must either upload a UPCS_FILE or provide values in UPC_LIST."
                    }

                    if (!params.STORE_ID?.trim()) {
                        error "STORE_ID parameter is required."
                    }

                    if (!params.DELIVERY_TYPE?.trim()) {
                        error "DELIVERY_TYPE parameter is required."
                    }

                    withEcr {
                        withAWS(
                            roleAccount: AWS_ACCOUNT_ID,
                            role: S3_ASSUME_ROLE,
                            roleSessionName: env.BUILD_TAG,
                            useNode: true
                        ) {
                            withEnv([
                                "ENVIRONMENT=${params.ENVIRONMENT}",
                                "UPC_FILE=${filePath}",
                                "UPC_LIST=${params.UPC_LIST}",
                                "STORE_ID=${params.STORE_ID}",
                                "DELIVERY_TYPE=${params.DELIVERY_TYPE}",
                                "BUILD_NUMBER=${env.BUILD_NUMBER}",
                                "CONCURRENCY=${env.CONCURRENCY}",
                                "TIMEOUT=${env.TIMEOUT}"
                            ]) {
                                dir('product-store-eligibility-check') {
                                    sh """
                                        docker compose run --rm --build \
                                            -e ENVIRONMENT \
                                            -e UPC_FILE \
                                            -e UPC_LIST \
                                            -e STORE_ID \
                                            -e DELIVERY_TYPE \
                                            -e BUILD_NUMBER \
                                            -e CONCURRENCY \
                                            -e TIMEOUT \
                                            ${volumeArg} \
                                            product-store-eligibility-check
                                    """
                                }
                            }
                        }
                    }
                }
            }
            post {
                success {
                    archiveArtifacts artifacts: "product-store-eligibility-check/artifacts/${env.BUILD_NUMBER}_eligibility_results.xlsx", followSymlinks: true
                }
            }
        }
    }

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