string GITHUB_REPOSITORY = 'insights-cross-app-data-tests'

def TestOptions = [
    'INSIGHTS-GO',
    'INSIGHTS-GO_FRESHNESS',
    'INSIGHTS-GO_DUPLICATES',
    'INSIGHTS-GO_STREAMS_CONSISTENCY',
    'INSIGHTS-GO_STREAMS_CONSISTENCY_BY_STORE'
]

pipeline {
    agent any

    parameters {
        string(name: 'ENV', defaultValue: 'prod', description: 'Environment to run the tests against. Example: qa, prod')
        choice(choices: TestOptions, description: 'Select which tests to run', name: 'TEST_OPTION')
        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.')
    }

    environment {
        ENV = "${params.ENV}"
    }

    triggers {
        cron('H */12 * * *')
        parameterizedCron('''
            0 15 * * 5 %TEST_OPTION=INSIGHTS-GO_FRESHNESS
            0 15 * * * %TEST_OPTION=INSIGHTS-GO_DUPLICATES
            0 16 * * * %TEST_OPTION=INSIGHTS-GO_STREAMS_CONSISTENCY
            0 17,5 * * * %TEST_OPTION=INSIGHTS-GO_STREAMS_CONSISTENCY_BY_STORE
        ''')
    }

    stages {
        stage('Set Build Name') {
            steps {
                script {
                    currentBuild.displayName = "#${BUILD_NUMBER} - ${params.TEST_OPTION}"
                }
            }
        }

        stage('Load Shared Libraries') {
            steps {
                library "jenkins-global-libraries@${params.SHARED_LIBRARIES_VERSION}"
            }
        }

        stage('Install Dependencies') {
            steps {
                script {
                    // Create and activate a virtual environment
                    sh '''
                        python3 -m venv venv
                        . venv/bin/activate
                        pip install --upgrade pip
                        pip install -r requirements.txt
                    '''
                }
            }
        }

        stage('Run Tests') {
            when {
                anyOf {
                    branch 'master'
                    expression { env.BRANCH_NAME == null || env.BRANCH_NAME == 'null' }
                }
            }
            steps {
                script {
                    withCredentials([aws(credentialsId: 'cucumber-tests')]) {
                        sh '''#!/bin/bash
                set -e
                . venv/bin/activate

                TEST_OPTION=${TEST_OPTION}
                PYTEST_BASE_CMD="pytest -s --rootdir=app"
                COMMON_ARGS="--report=test_results/report.html --split-report --template=html1/index.html"

                case "$TEST_OPTION" in
                  "INSIGHTS-GO")
                    $PYTEST_BASE_CMD app/src/tests/insights-go $COMMON_ARGS
                    ;;
                  "INSIGHTS-GO_FRESHNESS")
                    $PYTEST_BASE_CMD app/src/tests/insights-go/freshness $COMMON_ARGS
                    ;;
                  "INSIGHTS-GO_DUPLICATES")
                    $PYTEST_BASE_CMD app/src/tests/insights-go/duplicates $COMMON_ARGS
                    ;;
                  "INSIGHTS-GO_STREAMS_CONSISTENCY")
                    $PYTEST_BASE_CMD app/src/tests/insights-go/streams_consistency $COMMON_ARGS
                    ;;
                  "INSIGHTS-GO_STREAMS_CONSISTENCY_BY_STORE")
                    $PYTEST_BASE_CMD app/src/tests/insights-go/streams_consistency_by_store $COMMON_ARGS
                    ;;
                  *)
                    echo "Invalid test option: $TEST_OPTION"
                    exit 1
                    ;;
                esac
                        '''
                    }
                }
            }
            post {
                always {
                    archiveArtifacts artifacts: 'test_results/report.html', allowEmptyArchive: true
                    publishHTML(target: [
                        allowMissing: true,
                        alwaysLinkToLastBuild: true,
                        keepAll: true,
                        reportDir: 'test_results',
                        reportFiles: 'report.html',
                        reportName: 'HTML Report',
                        reportTitles: ''
                    ])
                }
            }
        }

        stage('Zip Test Results') {
            steps {
                script {
                    // Check if the test_results folder exists and zip its contents if it does
                    if (fileExists('test_results')) {
                        sh 'zip -r test_results.zip test_results/'
                    } else {
                        echo 'test_results folder does not exist, skipping zip step.'
                    }
                }
            }
        }

        stage('Archive Artifacts') {
            steps {
                script {
                    // Archive the zip file if it exists
                    if (fileExists('test_results.zip')) {
                        archiveArtifacts artifacts: 'test_results.zip', allowEmptyArchive: true
                    } else {
                        echo 'test_results.zip file does not exist, skipping archive step.'
                    }

                    // Archive the HTML report if it exists
                    if (fileExists('test_results/report.html')) {
                        archiveArtifacts artifacts: 'test_results/report.html', allowEmptyArchive: true
                    } else {
                        echo 'test_results/report.html file does not exist, skipping archive step.'
                    }
                }
            }
        }
    }

post {
        always {
            echo 'Cleaning up...'
            deleteDir()
        }

        success {
            echo 'Tests succeeded!'
        }

        failure {
            echo 'Tests failed!'
            archiveArtifacts artifacts: 'test_results/report.html', allowEmptyArchive: true
        }
    }
}
