name: Release

on:
  push:
    tags:
      - 'v*'

jobs:
  quality-checks:
    name: Verify Format, Lint, and Tests
    uses: ./.github/workflows/quality-checks.yml

  build:
    name: Build ${{ matrix.target }}
    needs: quality-checks
    runs-on: ${{ matrix.os }}
    strategy:
      matrix:
        include:
          - os: ubuntu-latest
            target: x86_64-unknown-linux-gnu
            artifact: bea
          - os: macos-latest
            target: x86_64-apple-darwin
            artifact: bea
          - os: macos-latest
            target: aarch64-apple-darwin
            artifact: bea
          - os: windows-latest
            target: x86_64-pc-windows-msvc
            artifact: bea.exe

    steps:
      - uses: actions/checkout@v6

      - name: Install stable toolchain
        uses: dtolnay/rust-toolchain@stable
        with:
          targets: ${{ matrix.target }}

      - name: Cache
        uses: Swatinem/rust-cache@v2
        with:
          key: ${{ matrix.target }}

      - name: Build
        run: cargo build --release --target ${{ matrix.target }}

      - name: Upload artifact
        uses: actions/upload-artifact@v6
        with:
          name: bea-${{ matrix.target }}
          path: target/${{ matrix.target }}/release/${{ matrix.artifact }}

  release:
    name: Create GitHub Release
    needs: build
    runs-on: ubuntu-latest
    permissions:
      contents: write
    steps:
      - uses: actions/checkout@v6

      - name: Download all artifacts
        uses: actions/download-artifact@v8
        with:
          path: artifacts

      - name: Rename artifacts
        run: |
          mv artifacts/bea-x86_64-unknown-linux-gnu/bea artifacts/bea-linux-x86_64
          mv artifacts/bea-x86_64-apple-darwin/bea artifacts/bea-macos-x86_64
          mv artifacts/bea-aarch64-apple-darwin/bea artifacts/bea-macos-aarch64
          mv artifacts/bea-x86_64-pc-windows-msvc/bea.exe artifacts/bea-windows-x86_64.exe

      - name: Install git-cliff
        uses: taiki-e/install-action@v2
        with:
          tool: git-cliff

      - name: Generate changelog
        run: git-cliff --latest --output RELEASE_NOTES.md

      - name: Create release
        uses: softprops/action-gh-release@v2
        with:
          files: |
            artifacts/bea-linux-x86_64
            artifacts/bea-macos-x86_64
            artifacts/bea-macos-aarch64
            artifacts/bea-windows-x86_64.exe
          body_path: RELEASE_NOTES.md
          make_latest: true

  publish:
    name: Publish to crates.io
    needs: release
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v6

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

      - name: Cache
        uses: Swatinem/rust-cache@v2

      - name: Publish
        run: cargo publish
        env:
          CARGO_REGISTRY_TOKEN: ${{ secrets.CARGO_REGISTRY_TOKEN }}
