name: Publish Package

on:
  push:
    tags:
      - 'v*'

jobs:
  publish:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4

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

      - name: Install wasm-pack
        run: curl https://rustwasm.github.io/wasm-pack/installer/init.sh -sSf | sh

      - name: Extract version from tag
        id: get_version
        run: echo "VERSION=${GITHUB_REF#refs/tags/v}" >> $GITHUB_OUTPUT

      - name: Update versions in manifests
        run: |
          VERSION=${{ steps.get_version.outputs.VERSION }}
          echo "Updating Cargo.toml to version $VERSION"
          # Atualiza a versão no Cargo.toml para bater com a tag
          sed -i "s/^version = \".*\"/version = \"$VERSION\"/" Cargo.toml

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

      - name: Build WASM package
        run: wasm-pack build --release --target bundler

      - name: Publish to npm
        run: |
          cd pkg
          tmp=$(mktemp)
          jq '.name = "@flagfy/build-engine"' package.json > "$tmp" && mv "$tmp" package.json
          
          echo "//registry.npmjs.org/:_authToken=${{ secrets.NPM_TOKEN }}" > .npmrc
          npm publish --access public
        env:
          NODE_AUTH_TOKEN: ${{ secrets.NPM_TOKEN }}