name: Reusable Android Build and Detekt

on:
  workflow_call:
    inputs:
      upload_artifacts:
        description: 'Whether to upload build and Detekt artifacts'
        required: false
        type: boolean
        default: true
    secrets:
      GRADLE_ENCRYPTION_KEY:
        required: false

jobs:
  build_and_detekt:
    runs-on: ubuntu-latest
    timeout-minutes: 35
    steps:
      - name: Checkout code
        uses: actions/checkout@v4
        with:
          submodules: 'recursive'
      - name: Validate Gradle wrapper
        uses: gradle/actions/wrapper-validation@v4
      - name: Set up JDK 21
        uses: actions/setup-java@v4
        with:
          java-version: '21'
          distribution: 'jetbrains'
      - name: Cache Gradle User Home
        uses: actions/cache@v4
        with:
          path: |
            ~/.gradle/caches
            ~/.gradle/wrapper
          key: gradle-${{ runner.os }}-${{ hashFiles('**/*.gradle*', '**/gradle-wrapper.properties', 'gradle.properties', 'settings.gradle*') }}
          restore-keys: |
            gradle-${{ runner.os }}-
      - name: Cache Android build cache
        uses: actions/cache@v4
        with:
          path: ~/.android/build-cache
          key: android-build-cache-${{ runner.os }}-${{ hashFiles('**/*.gradle*', '**/gradle-wrapper.properties', 'gradle.properties', 'settings.gradle*') }}
          restore-keys: |
            android-build-cache-${{ runner.os }}-
      - name: Setup Gradle
        uses: gradle/actions/setup-gradle@v4
        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 Detekt, Build, Lint, and Local Tests
        run: ./gradlew detekt lintFdroidDebug lintGoogleDebug assembleDebug testFdroidDebug testGoogleDebug --configuration-cache --scan --parallel
      - name: Upload F-Droid debug artifact
        if: ${{ inputs.upload_artifacts }}
        uses: actions/upload-artifact@v4
        with:
          name: fdroidDebug
          path: app/build/outputs/apk/fdroid/debug/app-fdroid-debug.apk
          retention-days: 14
      - name: Upload Google debug artifact
        if: ${{ inputs.upload_artifacts }}
        uses: actions/upload-artifact@v4
        with:
          name: googleDebug
          path: app/build/outputs/apk/google/debug/app-google-debug.apk
          retention-days: 14
      - name: Upload build and Detekt reports
        if: ${{ inputs.upload_artifacts }}
        uses: actions/upload-artifact@v4
        with:
          name: build-and-detekt-reports
          path: |
            app/build/reports
            **/build/reports/detekt
          retention-days: 14
