name: Download translation files from Localazy
on:
  workflow_dispatch:

jobs:
  download:
    runs-on: ubuntu-24.04
    permissions:
      contents: write

    steps:
      - name: Fail the workflow if not on the main branch or a release branch
        if: ${{ !(startsWith(github.ref_name, 'release/v') || github.ref_name == 'main') }}
        run: exit 1

      - name: Checkout the code
        uses: actions/checkout@v4.2.2

      - name: Install Node
        uses: actions/setup-node@v4.4.0
        with:
          node-version: 22

      - name: Install Localazy CLI
        run: npm install -g @localazy/cli

      - name: Compute the Localazy branch name
        id: branch
        # This will strip the "release/" prefix if present, keeping 'main' as-is
        run: echo "name=${GITHUB_REF_NAME#release/}" >> "$GITHUB_OUTPUT"

      - name: Download translations from Localazy
        run: localazy download -w "$LOCALAZY_WRITE_KEY" -b "$BRANCH"
        env:
          LOCALAZY_WRITE_KEY: ${{ secrets.LOCALAZY_WRITE_KEY }}
          BRANCH: ${{ steps.branch.outputs.name }}

      - name: Create Pull Request
        id: cpr
        uses: peter-evans/create-pull-request@v7.0.8
        with:
          sign-commits: true
          token: ${{ secrets.BOT_GITHUB_TOKEN }}
          branch-token: ${{ secrets.GITHUB_TOKEN }}
          branch: actions/localazy-download/${{ steps.branch.outputs.name }}
          delete-branch: true
          title: Translations updates for ${{ steps.branch.outputs.name }}
          labels: |
            T-Task
            A-I18n
          commit-message: Translations updates

      - name: Enable automerge
        run: gh pr merge --merge --auto "$PR_NUMBER"
        if: steps.cpr.outputs.pull-request-operation == 'created'
        env:
          GH_TOKEN: ${{ secrets.BOT_GITHUB_TOKEN }}
          PR_NUMBER: ${{ steps.cpr.outputs.pull-request-number }}
