name: Publish

on:
  push:
    tags:
      - "v*.*.*"

jobs:
  publish:
    runs-on: ubuntu-latest
    environment: crates-io
    permissions:
      contents: read
      id-token: write

    steps:
      - uses: actions/checkout@v4

      - uses: dtolnay/rust-toolchain@stable

      - uses: Swatinem/rust-cache@v2

      - name: Verify version matches tag
        run: |
          TOML_VERSION=$(cargo metadata --no-deps --format-version=1 | jq -r '.packages[0].version')
          TAG_VERSION="${GITHUB_REF_NAME#v}"
          if [ "$TOML_VERSION" != "$TAG_VERSION" ]; then
            echo "Version in Cargo.toml ($TOML_VERSION) does not match git tag ($TAG_VERSION)"
            exit 1
          fi

      - name: Dry run
        run: cargo publish --dry-run

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

      - name: Create GitHub Release
        uses: softprops/action-gh-release@v1
        with:
          tag_name: ${{ github.ref_name }}
          name: Release ${{ github.ref_name }}
          body: |
            See the [full changelog](https://github.com/grasp-labs/ds-common-logger-rs-lib/compare/${{ github.event.before }}...${{ github.sha }}) for details.
          draft: false
          prerelease: false
        env:
          GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}