import groovy.json.JsonOutput

def createEvent(operation) {
  def attributes = [
    target: "build",
    operation: operation,
    project: "hth_platform",
    repository: "backend",
    name: "${JOB_BASE_NAME}",
    ref: "${GIT_BRANCH}".minus('origin/'),
    commits: ["${GIT_COMMIT}"],
    resources: ["${RUN_TESTS_DISPLAY_URL}"]
  ]

  withCredentials([string(credentialsId: 'hth-bot-account-key', variable: 'ACCOUNT_KEY')]) {
    httpRequest(
      customHeaders: [[name: 'Authorization', value: "account_key='${ACCOUNT_KEY}'"]],
      acceptType: 'APPLICATION_JSON',
      contentType: 'APPLICATION_JSON',
      httpMode: 'POST',
      quiet: false,
      consoleLogResponseBody: true,
      requestBody: JsonOutput.toJson(attributes),
      url: 'https://lab.helixteamhub.com/api/events'
    )
  }
}

def runHelixTests() {
  sh'''
    bundle exec rspec -t helix_server:default -t ~helix_feature -t ~swagger_doc --profile 30
    bundle exec rspec -t helix_server:${JENKINS_HELIX_VERSION} -t ~helix_feature -t ~swagger_doc --profile 30
  '''
}

pipeline {
  agent { label 'main-node' }
  options {
    timestamps()
    ansiColor('xterm')
  }
  environment {
    COVERAGE = "0"
  }
  stages {
    stage('Cleanup') {
      steps {
        sh '''
          if ps aux | grep "\\[pilsner\\]"; then
            ps aux | grep "\\[pilsner\\]" | awk {'print $2'} | xargs kill
          fi

          curl --request DELETE "localhost:9250/index-p4search_test-000001"
          curl --request DELETE "localhost:9250/_ilm/policy/policy-p4search_test"
          curl --request DELETE "localhost:9250/_index_template/template-p4search_test"

          docker exec p4search_test rm -rf /opt/perforce/helix-p4search/jnl/IndexQueue.jnl

          docker restart p4search_test

          for i in $(seq 1 15)
          do
            echo "Waiting for P4 Search to start up $i / 15"
            if curl -s "localhost:1602/api/v1.2/ready" | grep -q '"OK"'; then
              echo "P4 Search started up successfully"
              break
            fi
            sleep 2
          done
        '''
      }
    }
    stage('Bundle') {
      steps {
        sh "bundle install"
      }
    }
    stage('Tests') {
      failFast true
      parallel {
        stage('Parallel') {
          environment {
            // Max 8 (Uses TEST_ENV_NUMBER 1-8)
            NUMBER_OF_PROCESSES = "4"
          }
          steps {
            sh '''
              bundle exec parallel_rspec ./spec --serialize-stdout --combine-stderr -n ${NUMBER_OF_PROCESSES} \
                --test-options '-t ~swagger_doc -t ~helix_server -t ~elasticsearch -t ~p4search_elasticsearch -t ~feature -t ~helix_feature --colour --format d --profile 30'
            '''
          }
        }
        stage('Elasticsearch') {
          environment {
            TEST_ENV_NUMBER = "9"
            JENKINS_HELIX_VERSION = "2026.1"
          }
          steps {
            sh "bundle exec rspec -t elasticsearch -t p4search_elasticsearch -t ~helix_feature -t ~swagger_doc --profile 30"
          }
        }
        stage('Features') {
          environment {
            TEST_ENV_NUMBER = "10"
          }
          steps {
            sh '''
              yarn install
              bundle exec rake webpacker:clobber
              bundle exec rake assets:clean
              bundle exec rake assets:precompile
              bundle exec rspec -t feature -t ~swagger_doc --profile 30
            '''
          }
        }
        stage('Test 26.1') {
          environment {
            TEST_ENV_NUMBER = "21"
            JENKINS_HELIX_VERSION = "2026.1"
          }
          steps {
            runHelixTests()
          }
        }
      }
    }
  }
  post {
    success {
      createEvent("completed")
    }
    failure {
      createEvent("failed")
    }
  }
}
