name: Build APK

on:
  workflow_call:
    inputs:
      version-name:
        required: true
        type: string
      build-type:
        required: true
        type: string
    secrets:
      google-services-json:
        required: true
      signing-key-store-base64:
        required: true
      signing-key-alias:
        required: true
      signing-key-password:
        required: true
      signing-store-password:
        required: true

jobs:
  build-apk:
    runs-on: ubuntu-latest
    permissions:
      contents: write

    steps:
      - uses: actions/checkout@v4

      - name: Setup JAVA 17
        uses: actions/setup-java@v3
        with:
          distribution: "temurin"
          java-version: 17

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

      - name: Setup Google Services
        run: echo ${{ secrets.google-services-json }} | base64 --decode > ./app/google-services.json

      - name: Set App Version
        run: |
          export VERSION_NAME='${{ inputs.version-name }}'
          sed -i "s/versionName.*/versionName \"${VERSION_NAME#v}\"/" app/build.gradle
          sed -i "s/versionCode.*/versionCode $(( ($(date +%s) - $(date -d "2022-06-15" +%s)) / 86400 ))/" app/build.gradle

      - name: Test
        run: ./gradlew test

      #1
      - name: Decode Keystore
        env:
          ENCODED_STRING: ${{ secrets.signing-key-store-base64 }}
          SIGNING_KEY_STORE_PATH: app/keystore.jks

        run: |
          echo $ENCODED_STRING > keystore-b64.txt
          base64 -d keystore-b64.txt > $SIGNING_KEY_STORE_PATH

      #2
      - name: Build ${{ inputs.build-type }} apk
        env:
          SIGNING_KEY_STORE_PATH: app/keystore.jks
          SIGNING_KEY_ALIAS: ${{ secrets.signing-key-alias }}
          SIGNING_KEY_PASSWORD: ${{ secrets.signing-key-password }}
          SIGNING_STORE_PASSWORD: ${{ secrets.signing-store-password }}
          TARGET: ${{ inputs.build-type }}
        run: ./gradlew assemble${TARGET^}

      - name: Build ${{ inputs.build-type }} bundle
        env:
          SIGNING_KEY_STORE_PATH: app/keystore.jks
          SIGNING_KEY_ALIAS: ${{ secrets.signing-key-alias }}
          SIGNING_KEY_PASSWORD: ${{ secrets.signing-key-password }}
          SIGNING_STORE_PASSWORD: ${{ secrets.signing-store-password }}
          TARGET: ${{ inputs.build-type }}
        run: ./gradlew bundle${TARGET^}
      #3
      - name: Upload ${{ inputs.build-type }} Build to Artifacts
        uses: actions/upload-artifact@v4
        with:
          name: ${{ inputs.build-type }}-artifacts
          path: |
            app/build/outputs/apk/${{ inputs.build-type }}/
            app/build/outputs/bundle/${{ inputs.build-type }}/
