name: Build AAB — WhatSMS Gateway

on:
  push:
    branches:
      - feat/whatsms-branding-ptpt
  workflow_dispatch:

jobs:
  build:
    runs-on: ubuntu-latest
    container:
      image: mingc/android-build-box:latest
      options: --network host

    steps:
      - name: Checkout
        uses: actions/checkout@v3

      - name: Configurar JDK 17
        run: |
          export JAVA_HOME=/usr/lib/jvm/java-17-openjdk-amd64
          echo "JAVA_HOME=/usr/lib/jvm/java-17-openjdk-amd64" >> $GITHUB_ENV
          echo "/usr/lib/jvm/java-17-openjdk-amd64/bin" >> $GITHUB_PATH
          java -version

      - name: Injectar google-services.json
        run: echo '${{ secrets.GOOGLE_SERVICES_JSON }}' > app/google-services.json

      - name: Decode keystore
        run: echo '${{ secrets.KEYSTORE_BASE64 }}' | base64 -d > app/keystore.jks

      - name: Build AAB release
        env:
          SIGNING_STORE_PASSWORD: ${{ secrets.SIGNING_STORE_PASSWORD }}
          SIGNING_KEY_ALIAS: ${{ secrets.SIGNING_KEY_ALIAS }}
          SIGNING_KEY_PASSWORD: ${{ secrets.SIGNING_KEY_PASSWORD }}
          JAVA_HOME: /usr/lib/jvm/java-17-openjdk-amd64
        run: |
          chmod +x gradlew
          ./gradlew bundleRelease --no-daemon --stacktrace

      - name: Publicar AAB como release Gitea
        env:
          GITEA_TOKEN: ${{ github.token }}
        run: |
          AAB=$(find app/build/outputs/bundle/release -name "*.aab" | head -1)
          echo "AAB encontrado: $AAB"
          # Criar release (ignora erro se tag ja existir)
          RESP=$(curl -s -X POST \
            -H "Authorization: token $GITEA_TOKEN" \
            -H "Content-Type: application/json" \
            https://git.descomplicar.pt/api/v1/repos/ealmeida/whatsms-gateway-android/releases \
            -d '{"tag_name":"v3.2.0-ci","name":"WhatSMS Gateway v3.2.0 CI","body":"Build automatico Gitea Actions","draft":false,"prerelease":true}')
          RELEASE_ID=$(echo "$RESP" | grep -o '"id":[0-9]*' | head -1 | cut -d: -f2)
          # Se release ja existe, obter ID por tag
          if [ -z "$RELEASE_ID" ] || [ "$RELEASE_ID" = "null" ]; then
            RELEASE_ID=$(curl -s \
              -H "Authorization: token $GITEA_TOKEN" \
              https://git.descomplicar.pt/api/v1/repos/ealmeida/whatsms-gateway-android/releases/tags/v3.2.0-ci \
              | grep -o '"id":[0-9]*' | head -1 | cut -d: -f2)
          fi
          echo "Release ID: $RELEASE_ID"
          # Upload AAB como asset da release
          curl -s -X POST \
            -H "Authorization: token $GITEA_TOKEN" \
            -H "Content-Type: application/octet-stream" \
            --data-binary "@$AAB" \
            "https://git.descomplicar.pt/api/v1/repos/ealmeida/whatsms-gateway-android/releases/${RELEASE_ID}/assets?name=whatsms-gateway-v3.2.0.aab"
          echo "Upload concluido!"
