name: Release

on:
  push:
    tags:
      - 'v*'
  workflow_dispatch:

permissions:
  contents: write
  id-token: write

jobs:
  build:
    strategy:
      fail-fast: false
      matrix:
        include:
          - os: ubuntu-latest
            target: x86_64-unknown-linux-gnu
            name: linux-x64-gnu
          - os: ubuntu-latest
            target: aarch64-unknown-linux-gnu
            name: linux-arm64-gnu
          - os: macos-latest
            target: x86_64-apple-darwin
            name: darwin-x64
          - os: macos-latest
            target: aarch64-apple-darwin
            name: darwin-arm64
          - os: windows-latest
            target: x86_64-pc-windows-msvc
            name: win32-x64-msvc

    runs-on: ${{ matrix.os }}
    name: Build - ${{ matrix.name }}

    steps:
      - uses: actions/checkout@v4

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

      - name: Install Rust
        uses: dtolnay/rust-toolchain@stable
        with:
          targets: ${{ matrix.target }}

      - name: Install cross-compilation tools (aarch64)
        if: matrix.target == 'aarch64-unknown-linux-gnu'
        run: |
          sudo apt-get update
          sudo apt-get install -y gcc-aarch64-linux-gnu

      - name: Install npm dependencies
        run: npm install

      - name: Build native module
        run: npm run build -- --target ${{ matrix.target }}
        env:
          CARGO_TARGET_AARCH64_UNKNOWN_LINUX_GNU_LINKER: aarch64-linux-gnu-gcc

      - name: Upload artifact
        uses: actions/upload-artifact@v4
        with:
          name: bindings-${{ matrix.name }}
          path: |
            *.node
          if-no-files-found: error

  publish:
    needs: build
    runs-on: ubuntu-latest
    name: Publish to npm

    steps:
      - uses: actions/checkout@v4

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

      - name: Install dependencies
        run: npm install

      - name: Download all artifacts
        uses: actions/download-artifact@v4
        with:
          path: artifacts

      - name: Move artifacts
        run: |
          ls -la artifacts/
          for dir in artifacts/bindings-*; do
            cp "$dir"/*.node . || true
          done
          ls -la *.node || echo "No .node files found"

      - name: List files
        run: ls -la

      - name: Publish to npm
        run: npm publish --access public
        env:
          NODE_AUTH_TOKEN: ${{ secrets.NPM_TOKEN }}

  publish-crates:
    needs: build
    runs-on: ubuntu-latest
    name: Publish to crates.io

    steps:
      - uses: actions/checkout@v4

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

      - name: Publish to crates.io
        run: cargo publish --token ${{ secrets.CARGO_TOKEN }}
