name: Build Android App (Capacitor)

on:
  push:
    branches:
      - main
      - master
    paths:
      - 'android-app/**'
      - '.github/workflows/build-android-app.yml'
  workflow_dispatch:

permissions:
  contents: read
  actions: write

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

      - name: Setup Node.js
        uses: actions/setup-node@v4
        with:
          node-version: '20'

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

      - name: Setup Android SDK
        uses: android-actions/setup-android@v3

      - name: Install dependencies
        run: npm install
        working-directory: android-app

      - name: Prepare UI
        run: npm run prepare-ui
        working-directory: android-app

      - name: Initialize Capacitor
        run: npx cap init "Plugin Compass" com.plugincompass.app --web-dir www
        working-directory: android-app

      - name: Add Android platform
        run: npx cap add android
        working-directory: android-app

      - name: Sync Capacitor
        run: npx cap sync android
        working-directory: android-app

      - name: Build APK
        run: |
          cd android
          chmod +x gradlew
          ./gradlew assembleDebug
        working-directory: android-app
        env:
          BACKEND_BASE_URL: ${{ secrets.BACKEND_BASE_URL }}

      - name: Upload APK artifact
        uses: actions/upload-artifact@v4
        with:
          name: plugin-compass-android-apk
          path: android-app/android/app/build/outputs/apk/debug/*.apk
          retention-days: 7
