name: Release

on:
  push:
    tags:
      - 'v*'

env:
  CARGO_TERM_COLOR: always

permissions:
  contents: write

jobs:
  create-release:
    name: Create GitHub Release
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v5

      - name: Create Release
        uses: softprops/action-gh-release@v3
        with:
          name: Release ${{ github.ref_name }}
          draft: false
          prerelease: false
          generate_release_notes: true

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

      - name: Check crates.io version
        id: crate
        run: |
          VERSION="${GITHUB_REF_NAME#v}"
          STATUS=$(curl --write-out "%{http_code}" --silent --output /dev/null \
            --header "User-Agent: feox-ann-release-workflow" \
            "https://crates.io/api/v1/crates/feox-ann/$VERSION")
          if [ "$STATUS" = "200" ]; then
            echo "published=true" >> "$GITHUB_OUTPUT"
            echo "feox-ann $VERSION is already published"
          elif [ "$STATUS" = "404" ]; then
            echo "published=false" >> "$GITHUB_OUTPUT"
            echo "feox-ann $VERSION is not published yet"
          else
            echo "Unexpected crates.io response: $STATUS"
            exit 1
          fi

      - name: Install Rust stable
        if: steps.crate.outputs.published == 'false'
        uses: dtolnay/rust-toolchain@stable

      - name: Verify package
        if: steps.crate.outputs.published == 'false'
        run: cargo package --verbose

      - name: Publish to crates.io
        if: steps.crate.outputs.published == 'false'
        run: cargo publish --token ${{ secrets.CARGO_REGISTRY_TOKEN }}
        env:
          CARGO_REGISTRY_TOKEN: ${{ secrets.CARGO_REGISTRY_TOKEN }}
