name: WASM Binding Tests

on:
  push:
    branches: [ main, master ]
    tags:
      - 'v*'
  pull_request:
    branches: [ main, master ]

permissions:
  contents: read
  id-token: write  # Required for OIDC

jobs:
  wasm-binding:
    name: Build and test WASM Binding
    runs-on: ubuntu-latest
    steps:
    - uses: actions/checkout@v4

    - name: Install Rust
      uses: dtolnay/rust-toolchain@stable
      with:
        targets: wasm32-unknown-unknown

    - name: Cache cargo
      uses: actions/cache@v4
      with:
        path: |
          ~/.cargo/registry
          ~/.cargo/git
          target
        key: wasm-cargo-${{ hashFiles('**/Cargo.lock') }}

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

    - name: Build WASM
      working-directory: bindings/wasm
      run: ./build.sh

    - name: Test WASM
      working-directory: bindings/wasm
      run: wasm-pack test --headless --firefox

    - name: Upload artifact
      uses: actions/upload-artifact@v4
      with:
        name: sentencex-wasm
        path: bindings/wasm/pkg
        if-no-files-found: error

  publish:
    name: Publish WASM Package
    if: startsWith(github.ref, 'refs/tags/v')
    needs: wasm-binding
    runs-on: ubuntu-latest
    steps:
    - uses: actions/checkout@v4

    - name: Setup Node.js
      uses: actions/setup-node@v4
      with:
        node-version: 22
        registry-url: 'https://registry.npmjs.org'

    - run: npm install -g npm@latest

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

    - name: Download artifact
      uses: actions/download-artifact@v4
      with:
        name: sentencex-wasm
        path: bindings/wasm/pkg

    - name: Publish WASM package
      working-directory: bindings/wasm/pkg
      run: npm publish --access public

