name: Generate release PR

on:
  workflow_dispatch:
    inputs:
      ref:
        description: 'Commit or branch to release'
        required: true
        default: 'master'
      version:
        description: 'Version number for the release (optional)'
        required: false
        default: ''

jobs:
  generate-release-pr:
    runs-on: ubuntu-latest
    steps:
      - name: Checkout
        uses: actions/checkout@08c6903cd8c0fde910a37f88322edcfb5dd907a8 # v5.0.0
        with:
          ref: ${{ github.event.inputs.ref }}
      - name: Bump package versions
        id: bump_package_versions
        shell: bash
        run: |
          declare -A packages=(
            [web]="desktop-client"
            [electron]="desktop-electron"
            [sync]="sync-server"
            [api]="api"
          )

          for key in "${!packages[@]}"; do
            pkg="${packages[$key]}"

            if [[ -n "${{ github.event.inputs.version }}" ]]; then
              version=$(node ./packages/ci-actions/bin/get-next-package-version.js \
                --package-json "./packages/$pkg/package.json" \
                --version "${{ github.event.inputs.version }}" \
                --update)
            else
              version=$(node ./packages/ci-actions/bin/get-next-package-version.js \
                --package-json "./packages/$pkg/package.json" \
                --type auto \
                --update)
            fi

            eval "NEW_${key^^}_VERSION=\"$version\""
          done

          echo "version=$NEW_WEB_VERSION" >> "$GITHUB_OUTPUT"
      - name: Create PR
        uses: peter-evans/create-pull-request@271a8d0340265f705b14b6d32b9829c1cb33d45e # v7.0.8
        with:
          token: ${{ secrets.ACTIONS_UPDATE_TOKEN }}
          commit-message: '🔖 (${{ steps.bump_package_versions.outputs.version }})'
          title: '🔖 (${{ steps.bump_package_versions.outputs.version }})'
          body: 'Generated by [generate-release-pr.yml](../tree/master/.github/workflows/generate-release-pr.yml)'
          branch: 'release/v${{ steps.bump_package_versions.outputs.version }}'
