name: CI

on:
  workflow_dispatch:
  pull_request:
    branches:
      - main
    paths-ignore:
      - 'README.md'
      - 'fastlane/**'
      - 'assets/**'
      - '.github/**'
  push:
    branches:
      - main
    paths-ignore:
      - 'README.md'
      - 'fastlane/**'
      - 'assets/**'
      - '.github/**'

jobs:
  build-client:
    runs-on: ubuntu-latest
    outputs:
      files: ${{ steps.step-output.outputs.files }}
    steps:
      - uses: actions/checkout@v4
        with:
          submodules: recursive

      - uses: gradle/actions/wrapper-validation@v4

      - name: Create and checkout branch
        if: github.event_name == 'pull_request'
        env:
          BRANCH: ${{ github.head_ref }}
        run: git checkout -B "$BRANCH"

      - name: Set up JDK 25
        uses: actions/setup-java@v4
        with:
          java-version: 25
          distribution: "temurin"
          cache: 'gradle'

      - name: Build debug APK
        run: |
          cd PipePipeClient
          ./gradlew assembleDebug lintDebug --stacktrace -DskipFormatKtlint

      - name: Upload APKs
        uses: actions/upload-artifact@v4
        with:
          name: all-apks-in-one(intermediates)
          retention-days: 1
          path: PipePipeClient/app/build/outputs/apk/debug/*.apk

      - name: Output filenames
        id: step-output
        run: |
          files=$(ls PipePipeClient/app/build/outputs/apk/debug)
          json_array="["
          first_file=true
          for file in $files; do
            if [ "$first_file" = false ]; then
              json_array+=", \"$file\""
            else
              json_array+="\"$file\""
              first_file=false
            fi
          done
          json_array+="]"
          echo "files=$json_array"
          echo "files=$json_array" >> "$GITHUB_OUTPUT"

  upload-apk:
    runs-on: ubuntu-latest
    needs: build-client
    strategy:
      matrix:
        file: ${{ fromJson(needs.build-client.outputs.files) }}
    steps:
      - name: Download APKs
        uses: actions/download-artifact@v4
        with:
          name: all-apks-in-one(intermediates)
          path: apks
          merge-multiple: true

      - name: Upload artifacts
        uses: actions/upload-artifact@v4
        with:
          name: ${{ matrix.file }}
          path: apks/${{ matrix.file }}
