name: Android CI

on:
  workflow_dispatch:
  push:
    branches: [ "main", "develop" ]
  pull_request:
    branches: [ "main", "develop" ]

jobs:
  verify:
    name: Test & Lint
    runs-on: ubuntu-latest

    steps:
    - name: Checkout code
      uses: actions/checkout@v4

    - name: Set up JDK 17
      uses: actions/setup-java@v4
      with:
        java-version: '17'
        distribution: 'temurin'

    - name: Setup Gradle
      uses: gradle/gradle-build-action@v3

    - name: Grant execute permission for gradlew
      run: chmod +x gradlew

    - name: Cache Gradle packages
      uses: actions/cache@v3
      with:
        path: |
          ~/.gradle/caches
          ~/.gradle/wrapper
        key: ${{ runner.os }}-gradle-${{ hashFiles('**/*.gradle*', '**/gradle-wrapper.properties') }}
        restore-keys: |
          ${{ runner.os }}-gradle-

    - name: Run unit tests
      run: ./gradlew testDebugUnitTest

    - name: Run lint
      run: ./gradlew lintDebug

    - name: Upload test reports
      if: always()
      uses: actions/upload-artifact@v4
      with:
        name: test-reports
        path: |
          **/build/test-results/
          **/build/reports/tests/

    - name: Upload lint results
      uses: actions/upload-artifact@v4
      if: always()
      with:
        name: lint-results
        path: '**/build/reports/lint-results-*.html'

  build:
    name: Build ${{ matrix.variant }}
    runs-on: ubuntu-latest
    needs: verify
    strategy:
      matrix:
        variant: [Debug, Release]

    steps:
    - name: Checkout code
      uses: actions/checkout@v4

    - name: Set up JDK 17
      uses: actions/setup-java@v4
      with:
        java-version: '17'
        distribution: 'temurin'

    - name: Setup Gradle
      uses: gradle/gradle-build-action@v3

    - name: Grant execute permission for gradlew
      run: chmod +x gradlew

    - name: Cache Gradle packages
      uses: actions/cache@v3
      with:
        path: |
          ~/.gradle/caches
          ~/.gradle/wrapper
        key: ${{ runner.os }}-gradle-${{ hashFiles('**/*.gradle*', '**/gradle-wrapper.properties') }}
        restore-keys: |
          ${{ runner.os }}-gradle-

    - name: Build ${{ matrix.variant }} APK
      run: ./gradlew assemble${{ matrix.variant }}

    - name: Upload ${{ matrix.variant }} APK
      uses: actions/upload-artifact@v4
      with:
        name: ${{ matrix.variant }}-apk
        path: app/build/outputs/apk/**/*.apk
