name: run-unit-tests

on:
  pull_request:
    types: [review_requested, ready_for_review, synchronize, opened, reopened]
    branches:
      - main

concurrency:
  group: ${{ github.workflow }}-${{ github.ref }}
  cancel-in-progress: true

jobs:
  pick-runner:

    if: github.event.pull_request.draft == false

    runs-on: ubuntu-latest
    outputs:
      runner: ${{ steps.choose.outputs.use-runner }}
    steps:

      - uses: actions/checkout@v4
      - id: choose
        uses: ./.github/actions/runner-fallback
        with:
          primary-runner: "self-hosted"
          fallback-runner: "ubuntu-latest"
          github-token: ${{ secrets.CUSTOM_GH_TOKEN }}
          

  run-unit-tests:
    needs: pick-runner
    if: github.event.pull_request.draft == false
    name: run-unit-tests
    runs-on: ${{ fromJson(needs.pick-runner.outputs.runner) }}
    env:
      CARGO_TERM_COLOR: always

    steps:
      - uses: actions/checkout@v4
      - name: Set up Rust
        uses: actions-rs/toolchain@v1
        with:
          toolchain: stable
          override: true
      - name: Install cargo-llvm-cov
        uses: taiki-e/install-action@cargo-llvm-cov

      - name: Run doctests
        run: cargo test --doc --release

      - name: Run unit tests with code coverage
        run: cargo llvm-cov --release --lcov --output-path lcov.info

      - name: Test docs generation
        run: cargo doc --no-deps --release

      - name: Upload coverage to Codecov
        uses: codecov/codecov-action@v3
        with:
          token: ${{ secrets.CODECOV_TOKEN }}
          files: lcov.info
          fail_ci_if_error: true
      - name: Upload test results to Codecov
        if: ${{ !cancelled() }}
        uses: codecov/test-results-action@v1
        with:
          token: ${{ secrets.CODECOV_TOKEN }}
