name: Build Android APK

on:
  push:
    tags:
      - 'v*'
  workflow_dispatch:

jobs:
  build:
    runs-on: ubuntu-latest
    timeout-minutes: 30

    steps:
      - uses: actions/checkout@v4

      - name: Setup Node
        uses: actions/setup-node@v4
        with:
          node-version: '20'
          cache: 'npm'
          cache-dependency-path: mobile/package-lock.json

      - name: Setup Java
        uses: actions/setup-java@v4
        with:
          distribution: 'temurin'
          java-version: '17'

      - name: Setup Gradle cache
        uses: gradle/actions/setup-gradle@v4

      - name: Install npm dependencies
        working-directory: mobile
        run: npm ci

      - name: Pre-bundle JS for debug embedding
        # Default RN debug builds don't embed JS bundle (expects Metro server).
        # We explicitly run Expo's `export:embed` so the resulting APK works
        # standalone on a phone without Metro running. This is also where
        # `EXPO_PUBLIC_*` env vars get inlined into the bundle.
        working-directory: mobile
        env:
          EXPO_PUBLIC_SENTRY_DSN: ${{ secrets.SENTRY_DSN }}
          EXPO_PUBLIC_SENTRY_ENVIRONMENT: ${{ vars.SENTRY_ENVIRONMENT || 'production' }}
        run: |
          mkdir -p android/app/src/main/assets android/app/src/main/res
          node node_modules/@expo/cli/build/bin/cli export:embed \
            --platform android \
            --dev false \
            --bundle-output android/app/src/main/assets/index.android.bundle \
            --assets-dest android/app/src/main/res

      - name: Build debug APK
        working-directory: mobile/android
        run: ./gradlew assembleDebug --no-daemon
        env:
          NODE_OPTIONS: --max_old_space_size=4096

      - name: Rename APK with version
        id: rename
        working-directory: mobile/android/app/build/outputs/apk/debug
        run: |
          REF_NAME="${{ github.ref_name }}"
          # Sanitize ref → safe filename component
          VERSION="${REF_NAME//[^a-zA-Z0-9._-]/_}"
          mv app-debug.apk "goon-${VERSION}-debug.apk"
          echo "apk=mobile/android/app/build/outputs/apk/debug/goon-${VERSION}-debug.apk" >> "$GITHUB_OUTPUT"

      - name: Upload APK artifact
        uses: actions/upload-artifact@v4
        with:
          name: goon-apk-${{ github.ref_name }}
          path: ${{ steps.rename.outputs.apk }}
          retention-days: 30

      - name: Attach APK to GitHub Release
        if: startsWith(github.ref, 'refs/tags/')
        uses: softprops/action-gh-release@v2
        with:
          files: ${{ steps.rename.outputs.apk }}
          fail_on_unmatched_files: true
          generate_release_notes: true
        env:
          GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
