name: Release

permissions:
  pull-requests: write
  contents: write

on:
  push:
    branches:
      - main
  workflow_dispatch:
    inputs:
      publish:
        description: 'Publish to crates.io'
        required: true
        default: false
        type: boolean

jobs:
  release-pr:
    name: Create Release PR
    runs-on: ubuntu-latest
    if: github.event_name == 'push'
    steps:
      - name: Checkout repository
        uses: actions/checkout@v6
        with:
          fetch-depth: 0

      - name: Install Rust toolchain
        uses: dtolnay/rust-toolchain@stable

      - name: Create or update release PR
        uses: release-plz/action@v0.5
        with:
          command: release-pr
        env:
          GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}

  release:
    name: Publish Release
    runs-on: ubuntu-latest
    environment: prod
    if: >-
      (github.event_name == 'workflow_dispatch' && inputs.publish) ||
      (github.event_name == 'push' && startsWith(github.event.head_commit.message, 'chore: release')) ||
      (github.event_name == 'push' && contains(github.event.head_commit.message, 'release-plz-'))
    steps:
      - name: Checkout repository
        uses: actions/checkout@v6
        with:
          fetch-depth: 0

      - name: Install Rust toolchain
        uses: dtolnay/rust-toolchain@stable

      - name: Publish to crates.io
        uses: release-plz/action@v0.5
        with:
          command: release
        env:
          GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
          CARGO_REGISTRY_TOKEN: ${{ secrets.CARGO_REGISTRY_TOKEN }}
