name: Build APK

on:
  push:
    branches: [main]
  workflow_dispatch:

env:
  ANDROID_HOME: ${{ runner.tool_cache }}/android-sdk
  ANDROID_SDK_ROOT: ${{ runner.tool_cache }}/android-sdk

jobs:
  build:
    runs-on: ubuntu-latest
    steps:
      - name: Checkout
        uses: actions/checkout@v4

      - name: Set up Node
        uses: actions/setup-node@v4
        with:
          node-version: 22

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

      - name: Install Android SDK
        run: |
          mkdir -p "$ANDROID_HOME/cmdline-tools"
          wget -q https://dl.google.com/android/repository/commandlinetools-linux-11076708_latest.zip -O /tmp/cmdtools.zip
          unzip -q /tmp/cmdtools.zip -d "$ANDROID_HOME/cmdline-tools"
          mv "$ANDROID_HOME/cmdline-tools/cmdline-tools" "$ANDROID_HOME/cmdline-tools/latest"
          yes | "$ANDROID_HOME/cmdline-tools/latest/bin/sdkmanager" --licenses > /dev/null
          "$ANDROID_HOME/cmdline-tools/latest/bin/sdkmanager" \
            "platform-tools" \
            "platforms;android-35" \
            "build-tools;35.0.0" \
            "ndk;27.1.12297006"

      - name: Install JS dependencies
        working-directory: carry-your-live
        run: npm ci

      - name: Generate debug keystore (signs the release APK)
        run: |
          keytool -genkeypair -v \
            -keystore carry-your-live/android/app/debug.keystore \
            -alias androiddebugkey -storepass android -keypass android \
            -keyalg RSA -keysize 2048 -validity 10000 \
            -dname "CN=Android Debug,O=Android,C=US"

      - name: Build release APK
        working-directory: carry-your-live/android
        run: ./gradlew assembleRelease

      - name: Upload APK
        uses: actions/upload-artifact@v4
        with:
          name: carry-your-live-release
          path: carry-your-live/android/app/build/outputs/apk/release/*.apk
