import com.sonymusic.Utils

def call(Map args) {
    def params = Utils.validateParams('k6Tests', args, [
        testFile: [type: String, required: true],
        backendService: [type: String, required: false],
        appUrl: [type: String, required: false],
        graphqlUrl: [type: String, required: false, defaultValue: 'https://qa-ows-grass.theorchard.io/graphql-router/graphql'],
        k6BackendStage1Duration: [type: String, required: false],
        k6BackendStage1Vus: [type: String, required: false],
        k6BackendStage2Duration: [type: String, required: false],
        k6BackendStage2Vus: [type: String, required: false],
        k6BackendStartVus: [type: String, required: false],
        k6FrontendVus: [type: String, required: false],
        k6FrontendStartTime: [type: String, required: false],
        k6FrontendDuration: [type: String, required: false],
        k6GracefulStopDuration: [type: String, required: false],
        k6MetricThresholds: [type: List, required: false],
        waitCompletion: [type: Boolean, required: false, defaultValue: true],
        propagateFailure: [type: Boolean, required: false, defaultValue: true],
    ])

    dir("k6-hybrid-performance-tests") {
            checkout([$class: 'GitSCM', branches: [[name: 'master']], doGenerateSubmoduleConfigurations: false, extensions: [], submoduleCfg: [], userRemoteConfigs: [[credentialsId: '577cbc72-7d9e-4eba-924c-ecbbe6de9805', url: "git@github.com:theorchard/k6-hybrid-performance-tests.git"]]])

        def credentials = [
            string(credentialsId: 'github_packages_token', variable: 'GITHUB_TOKEN')
        ]

        def mapping = [
            'testFile': ['TEST_FILE'],
            'backendService': ['BACKEND_SERVICE'],
            'appUrl': ['APP_URL'],
            'graphqlUrl': ['GRAPHQL_URL'],
            'k6BackendStage1Duration': ['K6_BACKEND_STAGE_1_DURATION'],
            'k6BackendStage1Vus': ['K6_BACKEND_STAGE_1_VUS'],
            'k6BackendStage2Duration': ['K6_BACKEND_STAGE_2_DURATION'],
            'k6BackendStage2Vus': ['K6_BACKEND_STAGE_2_VUS'],
            'k6BackendStartVus': ['K6_BACKEND_START_VUS'],
            'k6FrontendVus': ['K6_FRONTEND_VUS'],
            'k6FrontendStartTime': ['K6_FRONTEND_START_TIME'],
            'k6FrontendDuration': ['K6_FRONTEND_DURATION'],
            'k6GracefulStopDuration': ['K6_GRACEFUL_STOP_DURATION'],
            'k6MetricThresholds': ['K6_METRIC_THRESHOLDS']
        ]

        def envVars = []
        def buildParams = []
        mapping.each { key, env_names ->
            def value = params.get(key)
            if (value != null) {
                env_names.each { env_name ->
                    envVars.add("${env_name}=${value}")
                    buildParams << string(name: env_name, value: value.toString())
                }
            }
        }
        buildParams << string(name: 'RUN_TESTS', value: 'true')

        withCredentials(credentials) {
            withAWS(role: 'qa-k6-hybrid-performance-tests-role', roleAccount: '437795906767',
                roleSessionName: env.BUILD_TAG, useNode: true) {
                withEnv(envVars) {
                    if (params.waitCompletion) {
                        sh """
                            #!/bin/bash
                            make ci_run_docker_k6_test TEST_FILE=${env.TEST_FILE}
                        """
                    }
                    else {
                        build(job: 'k6Tests',
                            wait: params.waitCompletion,
                            propagate: params.propagateFailure,
                            parameters: buildParams
                        )
                        echo "Triggered downstream job at ${env.JENKINS_URL}job/k6Tests"
                    }
                }
            }
        archiveArtifacts artifacts: 'reports/html-report.html, reports/screenshots.zip, reports/summary.json', allowEmptyArchive: true
        }
    }
}
