name: Release

on:
  push:
    branches: [main]

jobs:
  # Checks crates.io — only publishes when version is unpublished (i.e., release PR was merged).
  # Safe to run on every push: no-op when version matches registry.
  # Order: cargo publish → git tag → GitHub Release. Fails safe at each step.
  release-plz-release:
    name: Publish & Release
    runs-on: ubuntu-latest
    permissions:
      contents: write
      pull-requests: read
    steps:
      - uses: actions/checkout@v6
        with:
          fetch-depth: 0
          persist-credentials: false

      - uses: dtolnay/rust-toolchain@stable

      - name: Generate app token
        id: app-token
        uses: actions/create-github-app-token@v3
        with:
          app-id: ${{ secrets.NIGHTWATCH_APP_ID }}
          private-key: ${{ secrets.NIGHTWATCH_APP_PRIVATE_KEY }}

      - name: Run release-plz release
        uses: release-plz/action@v0.5
        with:
          command: release
        env:
          GITHUB_TOKEN: ${{ steps.app-token.outputs.token }}
          CARGO_REGISTRY_TOKEN: ${{ secrets.CARGO_REGISTRY_TOKEN }}

  # Creates/updates the release PR with version bump + changelog.
  release-plz-pr:
    name: Release PR
    runs-on: ubuntu-latest
    permissions:
      contents: write
      pull-requests: write
    concurrency:
      group: release-plz-${{ github.ref }}
      cancel-in-progress: false
    steps:
      - uses: actions/checkout@v6
        with:
          fetch-depth: 0
          persist-credentials: false

      - uses: dtolnay/rust-toolchain@stable
      - uses: Swatinem/rust-cache@v2

      - name: Generate app token
        id: app-token
        uses: actions/create-github-app-token@v3
        with:
          app-id: ${{ secrets.NIGHTWATCH_APP_ID }}
          private-key: ${{ secrets.NIGHTWATCH_APP_PRIVATE_KEY }}

      - name: Run release-plz release-pr
        uses: release-plz/action@v0.5
        with:
          command: release-pr
        env:
          GITHUB_TOKEN: ${{ steps.app-token.outputs.token }}
          CARGO_REGISTRY_TOKEN: ${{ secrets.CARGO_REGISTRY_TOKEN }}
