name: Release

on:
  workflow_dispatch:
    inputs:
      version:
        type: choice
        required: true
        description: "Version number to bump"
        options:
          - patch
          - minor
          - major

env:
  FORCE_JAVASCRIPT_ACTIONS_TO_NODE24: true

permissions:
  contents: write
  issues: write
  pull-requests: write

jobs:
  publish-dry-run:
    name: "Runs cargo publish --dry-run"
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v6

      - uses: dtolnay/rust-toolchain@stable
        with:
          toolchain: stable

      - name: publish crate
        run: cargo publish --dry-run

  release:
    name: Create Release
    needs: publish-dry-run
    runs-on: ubuntu-latest
    steps:
      - name: Generate Githup App Token
        id: generate_token
        uses: tibdex/github-app-token@v2
        with:
          app_id: ${{ secrets.APP_ID }}
          private_key: ${{ secrets.APP_PRIVATE_KEY }}

      - name: Checkout code
        uses: actions/checkout@v6
        with:
          fetch-depth: 0
          token: ${{ steps.generate_token.outputs.token }}

      - name: Setup Rust
        uses: dtolnay/rust-toolchain@stable
        with:
          toolchain: stable

      - name: Install `cargo-edit`
        run: cargo install cargo-edit

      - id: cargo-set-version
        name: Set Version
        run: cargo set-version --bump ${{ inputs.version }}

      - name: Set Crate Version as Environment Variable
        run: |
          CARGO_TOML_VERSION=$(awk -F ' = ' '$1 ~ /version/ { gsub(/[\"]/, "", $2); printf("%s",$2) }' Cargo.toml)
          echo "CRATE_VERSION=$CARGO_TOML_VERSION" >> $GITHUB_ENV

      - name: Create Commit
        run: |
          git config --global user.name 'github-actions[bot]'
          git config --global user.email 'github-actions[bot]@users.noreply.github.com'
          git add .
          git commit -m "chore: bump version to v$CRATE_VERSION"

      - name: Push changes
        uses: ad-m/github-push-action@master
        with:
          github_token: ${{ steps.generate_token.outputs.token }}
          branch: ${{ github.ref }}

      - name: Login to Crates.io
        run: cargo login ${CARGO_REGISTRY_TOKEN}
        env:
          CARGO_REGISTRY_TOKEN: ${{ secrets.CARGO_REGISTRY_TOKEN }}

      - name: Publish crate
        run: cargo publish

      - name: Create Release
        id: create_release
        uses: actions/github-script@v9
        env:
          CRATE_VERSION: ${{ env.CRATE_VERSION }}
        with:
          script: |
            await github.request(`POST /repos/${{ github.repository }}/releases`, {
              tag_name: `v${process.env.CRATE_VERSION}`,
              generate_release_notes: true
            });
