name: Unit Tests

on:
  workflow_dispatch:
  push:
    branches:
      - main
      - "release/**"
    paths:
      - "**.go"
      - "**/go.mod"
      - "**/go.sum"
      - "**/testdata/**"
      - ".github/workflows/test-unittest.yml"
  pull_request:
    paths:
      - "internal/constellation/helm/**"
      - "**.go"
      - "**/go.mod"
      - "**/go.sum"
      - "**/testdata/**"
      - ".github/workflows/test-unittest.yml"

jobs:
  test-unittest:
    runs-on: [arc-runner-set]
    permissions:
      id-token: write
      contents: read
      pull-requests: write
    steps:
      - name: Checkout
        uses: actions/checkout@a5ac7e51b41094c92402da3b24376905380afc29 # v4.1.6
        with:
          ref: ${{ !github.event.pull_request.head.repo.fork && github.head_ref || '' }}
          fetch-depth: 0

      - name: Setup bazel
        uses: ./.github/actions/setup_bazel_nix
        with:
          useCache: "rbe"
          rbePlatform: "ubuntu-22.04"

      - name: Install AWS cli
        run: |
          curl -fsSL "https://awscli.amazonaws.com/awscli-exe-linux-x86_64.zip" -o "awscliv2.zip"
          unzip awscliv2.zip
          sudo ./aws/install
          rm -rf awscliv2.zip aws

      - name: Login to AWS (IAM role)
        uses: aws-actions/configure-aws-credentials@e3dd6a429d7300a6a4c196c26e071d42e0343502 # v4.0.2
        with:
          role-to-assume: arn:aws:iam::795746500882:role/GithubActionGocoverage
          aws-region: eu-central-1

      - name: Unit Tests
        env:
          TMPDIR: ${{ runner.temp }}
        run: bazel test //... --test_output=errors --config=nostamp --remote_download_minimal

      - name: Coverage
        id: coverage
        run: |
          bazel run //bazel/ci:gocoverage_diff --config=nostamp
          lines=$(wc -l < coverage_diff.md)
          uploadable=$([[ ${lines} -gt 3 ]] && echo "true" || echo "false")
          echo "uploadable=$uploadable" | tee -a "$GITHUB_OUTPUT"

      - name: Comment coverage
        if: steps.coverage.outputs.uploadable == 'true' && github.event_name == 'pull_request'
        uses: marocchino/sticky-pull-request-comment@331f8f5b4215f0445d3c07b4967662a32a2d3e31 # v2.9.0
        with:
          header: coverage
          path: coverage_diff.md
          recreate: true

      - name: Upload coverage
        if: github.ref_name == 'main'
        run: |
          cat coverage_result.json
          aws s3 cp coverage_result.json s3://constellation-ci/gocoverage/coverage_main.json
          echo "coverage uploaded to s3://constellation-ci/gocoverage/coverage_main.json"