name: Reusable Android Instrumented Tests

on:
  workflow_call:
    inputs:
      upload_artifacts:
        description: 'Whether to upload Android test reports'
        required: false
        type: boolean
        default: true
      api_levels:
        description: 'JSON array string of API levels to run tests on (e.g., `[35]` or `[26, 35]`)'
        required: false
        type: string
        default: '[26, 35]' # Default to running both if not specified by caller
    secrets:
      GRADLE_ENCRYPTION_KEY:
        required: false
      CODECOV_TOKEN:
        required: true

jobs:
  androidTest:
    runs-on: ubuntu-latest
    timeout-minutes: 25
    strategy:
      matrix:
        api-level: ${{ fromJson(inputs.api_levels) }} # Use the input to define the matrix
    steps:
      - name: Checkout code
        uses: actions/checkout@v5
        with:
          submodules: 'recursive'

      - name: Set up JDK 21
        uses: actions/setup-java@v5
        with:
          java-version: '21'
          distribution: 'jetbrains'
        env:
          GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}

      - name: Enable KVM group perms
        run: |
          echo 'KERNEL=="kvm", GROUP="kvm", MODE="0666", OPTIONS+="static_node=kvm"' | sudo tee /etc/udev/rules.d/99-kvm4all.rules
          sudo udevadm control --reload-rules
          sudo udevadm trigger --name-match=kvm

      - name: Setup Gradle
        uses: gradle/actions/setup-gradle@v5
        with:
          cache-encryption-key: ${{ secrets.GRADLE_ENCRYPTION_KEY }}
          build-scan-publish: true
          build-scan-terms-of-use-url: 'https://gradle.com/terms-of-service'
          build-scan-terms-of-use-agree: 'yes'
          add-job-summary: always

      - name: Run Android Instrumented Tests
        uses: reactivecircus/android-emulator-runner@v2
        env:
          ANDROID_EMULATOR_WAIT_TIME_BEFORE_KILL: 60
        with:
          api-level: ${{ matrix.api-level }}
          arch: x86_64
          force-avd-creation: false
          emulator-options: -no-snapshot-save -no-window -gpu swiftshader_indirect -noaudio -no-boot-anim -no-metrics -camera-back none
          disable-animations: true
          script: ./gradlew :app:connectedFdroidDebugAndroidTest :app:connectedGoogleDebugAndroidTest --configuration-cache --scan && ( killall -INT crashpad_handler || true )
      - name: Upload test results to Codecov
        if: ${{ !cancelled() }}
        uses: codecov/test-results-action@v1
        with:
          token: ${{ secrets.CODECOV_TOKEN }}
      - name: Upload Test Results
        if: ${{ inputs.upload_artifacts }}
        uses: actions/upload-artifact@v4
        with:
          name: android-test-reports-api-${{ matrix.api-level }}
          path: app/build/outputs/androidTest-results/
          retention-days: 14
