// Jenkinsfile for the `songwhip-api-send-emails-for-incomplete-presaves` job on scheduler.theorchard.io

// AWS Credentials Configuration
String QA_AWS_ACCOUNT_ID = '619719722105'
String QA_AWS_ROLE = 'qa-songwhip-api-scheduler-role'
String QA_SECRET_ID = 'qa/songwhip-api/SONGWHIP_WEBHOOK_KEY'
String PROD_AWS_ACCOUNT_ID = '926734670777'
String PROD_AWS_ROLE = 'prod-songwhip-api-scheduler-role'
String PROD_SECRET_ID = 'prod/songwhip-api/SONGWHIP_WEBHOOK_KEY'

pipeline {
    agent any

     triggers {
         cron('H 0 * * *')
     }

    options {
        ansiColor('xterm')
        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.')
    }

    stages {
        stage('Load Shared Libraries') {
            steps {
                library "jenkins-global-libraries@${params.SHARED_LIBRARIES_VERSION}"
            }
        }
        stage('Send emails for incomplete presaves - QA') {
            parallel {
                stage ('Send emails for albums on QA') {
                    steps {
                        withAWS(roleAccount: QA_AWS_ACCOUNT_ID, role: QA_AWS_ROLE, roleSessionName: env.BUILD_TAG, useNode: true) {
                            withSecrets(secrets: [
                                [
                                    id: QA_SECRET_ID,
                                    environmentVariable: 'QA_KEY'
                                ]
                            ]) {
                                sh(
                                    script: """
                                        set -e

                                        # Configuration
                                        export URL="https://api-staging.songwhip.com/v3/albums/send-notifications"

                                        # Source common API caller functions
                                        readonly MAX_RETRIES=3
                                        readonly TIMEOUT=30

                                        # Function to call API with retry logic
                                        call_api() {
                                            local env_name="\$1"
                                            local url="\$2"
                                            local key="\$3"
                                            local body="\$4"
                                            local retry=0

                                            echo "Starting API call for \$env_name environment"

                                            while [ \$retry -lt \$MAX_RETRIES ]; do
                                                echo "[\$(date)] Attempt \$((retry+1))/\$MAX_RETRIES for \$env_name"

                                                # Make API call with curl
                                                HTTP_STATUS=\$(curl -f -s -o /tmp/response.txt -w "%{http_code}" \\
                                                  --max-time \$TIMEOUT \\
                                                  -X POST \\
                                                  -H "Content-Type: application/json" \\
                                                  -H "songwhip-webhook-key: \$key" \\
                                                  -d "\$body" \\
                                                  "\$url")

                                                # Check if request was successful
                                                if [ "\$HTTP_STATUS" -eq 200 ] || [ "\$HTTP_STATUS" -eq 201 ] || [ "\$HTTP_STATUS" -eq 204 ]; then
                                                    echo "[SUCCESS] \$env_name: HTTP \$HTTP_STATUS"
                                                    return 0
                                                else
                                                    echo "[FAILED] \$env_name: HTTP \$HTTP_STATUS"

                                                    # Retry with exponential backoff if not last attempt
                                                    if [ \$retry -lt \$((MAX_RETRIES-1)) ]; then
                                                        sleep_time=\$((2 ** (retry+1)))
                                                        echo "Retrying in \${sleep_time}s..."
                                                        sleep \$sleep_time
                                                    fi
                                                fi
                                                retry=\$((retry+1))
                                            done

                                            echo "[ERROR] \$env_name: All \$MAX_RETRIES retry attempts failed"
                                            exit 1
                                        }

                                        # Execute API call and capture response
                                        call_api "QA Albums" "\$URL" "\$QA_KEY" "{}"

                                        # Echo the response
                                        echo "QA Albums Response:"
                                        cat /tmp/response.txt || echo "No response file found"
                                      """
                                )
                            }
                        }
                    }
                }
                stage ('Send emails for prereleases on QA') {
                    steps {
                        withAWS(roleAccount: QA_AWS_ACCOUNT_ID, role: QA_AWS_ROLE, roleSessionName: env.BUILD_TAG, useNode: true) {
                            withSecrets(secrets: [
                                [
                                    id: QA_SECRET_ID,
                                    environmentVariable: 'QA_KEY'
                                ]
                            ]) {
                                sh(
                                    script: """
                                        set -e

                                        # Configuration
                                        export URL="https://api-staging.songwhip.com/v3/prereleases/send-notifications"

                                        # Source common API caller functions
                                        readonly MAX_RETRIES=3
                                        readonly TIMEOUT=30

                                        # Function to call API with retry logic
                                        call_api() {
                                            local env_name="\$1"
                                            local url="\$2"
                                            local key="\$3"
                                            local body="\$4"
                                            local retry=0

                                            echo "Starting API call for \$env_name environment"

                                            while [ \$retry -lt \$MAX_RETRIES ]; do
                                                echo "[\$(date)] Attempt \$((retry+1))/\$MAX_RETRIES for \$env_name"

                                                # Make API call with curl
                                                HTTP_STATUS=\$(curl -f -s -o /tmp/response.txt -w "%{http_code}" \\
                                                  --max-time \$TIMEOUT \\
                                                  -X POST \\
                                                  -H "Content-Type: application/json" \\
                                                  -H "songwhip-webhook-key: \$key" \\
                                                  -d "\$body" \\
                                                  "\$url")

                                                # Check if request was successful
                                                if [ "\$HTTP_STATUS" -eq 200 ] || [ "\$HTTP_STATUS" -eq 201 ] || [ "\$HTTP_STATUS" -eq 204 ]; then
                                                    echo "[SUCCESS] \$env_name: HTTP \$HTTP_STATUS"
                                                    return 0
                                                else
                                                    echo "[FAILED] \$env_name: HTTP \$HTTP_STATUS"

                                                    # Retry with exponential backoff if not last attempt
                                                    if [ \$retry -lt \$((MAX_RETRIES-1)) ]; then
                                                        sleep_time=\$((2 ** (retry+1)))
                                                        echo "Retrying in \${sleep_time}s..."
                                                        sleep \$sleep_time
                                                    fi
                                                fi
                                                retry=\$((retry+1))
                                            done

                                            echo "[ERROR] \$env_name: All \$MAX_RETRIES retry attempts failed"
                                            exit 1
                                        }

                                        # Execute API call and capture response
                                        call_api "QA Prereleases" "\$URL" "\$QA_KEY" "{}"

                                        # Echo the response
                                        echo "QA Prereleases Response:"
                                        cat /tmp/response.txt || echo "No response file found"
                                      """
                                )
                            }
                        }
                    }
                }
            }
        }
        stage('Send emails for incomplete presaves - PROD') {
            parallel {
                stage ('Send emails for albums on PROD') {
                    steps {
                        withAWS(roleAccount: PROD_AWS_ACCOUNT_ID, role: PROD_AWS_ROLE, roleSessionName: env.BUILD_TAG, useNode: true) {
                            withSecrets(secrets: [
                                [
                                    id: PROD_SECRET_ID,
                                    environmentVariable: 'PROD_KEY'
                                ]
                            ]) {
                                sh(
                                    script: """
                                        set -e

                                        # Configuration
                                        export URL="https://api.songwhip.com/v3/albums/send-notifications"

                                        # Source common API caller functions
                                        readonly MAX_RETRIES=3
                                        readonly TIMEOUT=30

                                        # Function to call API with retry logic
                                        call_api() {
                                            local env_name="\$1"
                                            local url="\$2"
                                            local key="\$3"
                                            local body="\$4"
                                            local retry=0

                                            echo "Starting API call for \$env_name environment"

                                            while [ \$retry -lt \$MAX_RETRIES ]; do
                                                echo "[\$(date)] Attempt \$((retry+1))/\$MAX_RETRIES for \$env_name"

                                                # Make API call with curl
                                                HTTP_STATUS=\$(curl -f -s -o /tmp/response.txt -w "%{http_code}" \\
                                                  --max-time \$TIMEOUT \\
                                                  -X POST \\
                                                  -H "Content-Type: application/json" \\
                                                  -H "songwhip-webhook-key: \$key" \\
                                                  -d "\$body" \\
                                                  "\$url")

                                                # Check if request was successful
                                                if [ "\$HTTP_STATUS" -eq 200 ] || [ "\$HTTP_STATUS" -eq 201 ] || [ "\$HTTP_STATUS" -eq 204 ]; then
                                                    echo "[SUCCESS] \$env_name: HTTP \$HTTP_STATUS"
                                                    return 0
                                                else
                                                    echo "[FAILED] \$env_name: HTTP \$HTTP_STATUS"

                                                    # Retry with exponential backoff if not last attempt
                                                    if [ \$retry -lt \$((MAX_RETRIES-1)) ]; then
                                                        sleep_time=\$((2 ** (retry+1)))
                                                        echo "Retrying in \${sleep_time}s..."
                                                        sleep \$sleep_time
                                                    fi
                                                fi
                                                retry=\$((retry+1))
                                            done

                                            echo "[ERROR] \$env_name: All \$MAX_RETRIES retry attempts failed"
                                            exit 1
                                        }

                                        # Execute API call and capture response
                                        call_api "PROD Albums" "\$URL" "\$PROD_KEY" "{}"

                                        # Echo the response
                                        echo "PROD Albums Response:"
                                        cat /tmp/response.txt || echo "No response file found"
                                      """
                                )
                            }
                        }
                    }
                }
                stage ('Send emails for prereleases on PROD') {
                    steps {
                        withAWS(roleAccount: PROD_AWS_ACCOUNT_ID, role: PROD_AWS_ROLE, roleSessionName: env.BUILD_TAG, useNode: true) {
                            withSecrets(secrets: [
                                [
                                    id: PROD_SECRET_ID,
                                    environmentVariable: 'PROD_KEY'
                                ]
                            ]) {
                                sh(
                                    script: """
                                        set -e

                                        # Configuration
                                        export URL="https://api.songwhip.com/v3/prereleases/send-notifications"

                                        # Source common API caller functions
                                        readonly MAX_RETRIES=3
                                        readonly TIMEOUT=30

                                        # Function to call API with retry logic
                                        call_api() {
                                            local env_name="\$1"
                                            local url="\$2"
                                            local key="\$3"
                                            local body="\$4"
                                            local retry=0

                                            echo "Starting API call for \$env_name environment"

                                            while [ \$retry -lt \$MAX_RETRIES ]; do
                                                echo "[\$(date)] Attempt \$((retry+1))/\$MAX_RETRIES for \$env_name"

                                                # Make API call with curl
                                                HTTP_STATUS=\$(curl -f -s -o /tmp/response.txt -w "%{http_code}" \\
                                                  --max-time \$TIMEOUT \\
                                                  -X POST \\
                                                  -H "Content-Type: application/json" \\
                                                  -H "songwhip-webhook-key: \$key" \\
                                                  -d "\$body" \\
                                                  "\$url")

                                                # Check if request was successful
                                                if [ "\$HTTP_STATUS" -eq 200 ] || [ "\$HTTP_STATUS" -eq 201 ] || [ "\$HTTP_STATUS" -eq 204 ]; then
                                                    echo "[SUCCESS] \$env_name: HTTP \$HTTP_STATUS"
                                                    return 0
                                                else
                                                    echo "[FAILED] \$env_name: HTTP \$HTTP_STATUS"

                                                    # Retry with exponential backoff if not last attempt
                                                    if [ \$retry -lt \$((MAX_RETRIES-1)) ]; then
                                                        sleep_time=\$((2 ** (retry+1)))
                                                        echo "Retrying in \${sleep_time}s..."
                                                        sleep \$sleep_time
                                                    fi
                                                fi
                                                retry=\$((retry+1))
                                            done

                                            echo "[ERROR] \$env_name: All \$MAX_RETRIES retry attempts failed"
                                            exit 1
                                        }

                                        # Execute API call and capture response
                                        call_api "PROD Prereleases" "\$URL" "\$PROD_KEY" "{}"

                                        # Echo the response
                                        echo "PROD Prereleases Response:"
                                        cat /tmp/response.txt || echo "No response file found"
                                      """
                                )
                            }
                        }
                    }
                }
            }
        }
    }

    post {
        failure {
            echo 'Pipeline failed. Check logs for details.'
        }
        success {
            echo 'Email sending job completed successfully.'
        }
    }
}
