name: Flutter Build (Signed APK)
on: [push, pull_request, workflow_dispatch]

env:
  FLUTTER_PATH: "./flutter" # Путь к подмодулю Flutter

jobs:
  build:
    runs-on: docker
    steps:
      # 1. Checkout репозиторий + подмодули
      - name: Checkout code
        uses: actions/checkout@v4
        with:
          submodules: recursive

      # 2. Устанавливаем Flutter из подмодуля
      - name: Setup Flutter
        run: |
          echo "$GITHUB_WORKSPACE/$FLUTTER_PATH/bin"
          echo "$GITHUB_WORKSPACE/$FLUTTER_PATH/bin" >> $GITHUB_PATH
          echo $GITHUB_PATH
          flutter --version

      # 3. Создаем key.properties и загружаем ключ (секреты Forgejo)
      - name: Setup signing keys
        run: |
          # Создаем директорию для ключа
          mkdir -p android/app

          # Создаем key.properties
          echo "storePassword=${{ secrets.KEY_PASSWORD }}" > android/key.properties
          echo "keyPassword=${{ secrets.KEY_PASSWORD }}" >> android/key.properties
          echo "keyAlias=upload" >> android/key.properties
          echo "storeFile=key.jks" >> android/key.properties

          # Декодируем base64-ключ (хранится в secrets.KEYSTORE_BASE64)
          echo "${{ secrets.KEYSTORE_BASE64 }}" | base64 --decode > android/app/key.jks

      # 4. Кэширование
      - name: Cache dependencies
        uses: actions/cache@v4
        with:
          path: |
            ${{ env.FLUTTER_PATH }}/bin/cache
            .dart_tool
          key: ${{ runner.os }}-flutter-${{ hashFiles('pubspec.lock') }}

      # 5. Восстанавливаем зависимости
      - name: Get packages
        run: flutter pub get

      # 6. Собираем подписанный APK
      - name: Build signed APK
        run: |
          flutter build apk --release --split-per-abi

      # 7. Сохраняем артефакты
      - name: Upload artifacts
        uses: actions/upload-artifact@v4
        with:
          name: signed-apks
          path: build/app/outputs/flutter-apk/*.apk
