name: Build and Release Gem
on:
  workflow_run:
    workflows: ["Tests"]
    types:
      - completed
  workflow_dispatch:

jobs:
  release:
    name: Release to GitHub Packages
    runs-on: ubuntu-latest
    if: ${{ github.event.workflow_run.conclusion == 'success' || github.event_name == 'workflow_dispatch' }}
    permissions:
      packages: write
      contents: write

    steps:
    - uses: fac/ruby-gem-setup-credentials-action@v2
      with:
        token: ${{ secrets.github_token }}

    # Build the gem package
    - uses: actions/checkout@v4
    - uses: ruby/setup-ruby@v1
      with:
        bundler-cache: true
    - run: bundle exec rake build

    # Release production gem version from default branch
    - name: Release
      if:   github.ref == 'refs/heads/main'
      uses: fac/ruby-gem-push-action@v2
      with:
        key: github

    # PR branch builds will release pre-release gems
    - name: Pre-Release
      if:   github.ref != 'refs/heads/main'
      uses: fac/ruby-gem-push-action@v2
      with:
        key: github
        pre-release: true