name: Release

on:
  push:
    tags:
      - 'v*'  # Trigger on version tags like v0.1.18

env:
  CARGO_TERM_COLOR: always

jobs:
  # Validate version consistency across files
  validate-version:
    runs-on: ubuntu-latest
    outputs:
      version: ${{ steps.get-version.outputs.version }}
    steps:
      - uses: actions/checkout@v4

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

      - name: Validate Cargo.toml version
        run: |
          CARGO_VERSION=$(grep '^version' Cargo.toml | head -1 | sed 's/.*"\(.*\)".*/\1/')
          if [ "$CARGO_VERSION" != "${{ steps.get-version.outputs.version }}" ]; then
            echo "ERROR: Cargo.toml version ($CARGO_VERSION) doesn't match tag (${{ steps.get-version.outputs.version }})"
            exit 1
          fi
          echo "✓ Cargo.toml version matches: $CARGO_VERSION"

      - name: Validate package.json version
        run: |
          NPM_VERSION=$(node -p "require('./package.json').version")
          if [ "$NPM_VERSION" != "${{ steps.get-version.outputs.version }}" ]; then
            echo "ERROR: package.json version ($NPM_VERSION) doesn't match tag (${{ steps.get-version.outputs.version }})"
            exit 1
          fi
          echo "✓ package.json version matches: $NPM_VERSION"

  # Build and test Rust
  test-rust:
    runs-on: ubuntu-latest
    needs: validate-version
    steps:
      - uses: actions/checkout@v4

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

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

      - name: Run tests
        run: cargo test --verbose

  # Build WASM and test
  test-wasm:
    runs-on: ubuntu-latest
    needs: validate-version
    steps:
      - uses: actions/checkout@v4

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

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

      - name: Build WASM
        run: wasm-pack build --target web --out-dir pkg

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

      - name: Run WASM tests
        run: wasm-pack test --headless --chrome --release

  # Publish to crates.io
  publish-crates:
    runs-on: ubuntu-latest
    needs: [validate-version, test-rust]
    steps:
      - uses: actions/checkout@v4

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

      - name: Publish to crates.io
        env:
          CARGO_REGISTRY_TOKEN: ${{ secrets.CARGO_REGISTRY_TOKEN }}
        run: |
          cargo publish --verbose --allow-dirty 2>&1 | tee /tmp/cargo-publish.log || {
            if grep -q "already exists" /tmp/cargo-publish.log; then
              echo "Version already published to crates.io, skipping"
              exit 0
            else
              exit 1
            fi
          }

  # Publish to npm
  publish-npm:
    runs-on: ubuntu-latest
    needs: [validate-version, test-wasm]
    environment: npm-publish
    permissions:
      contents: read
      id-token: write
    steps:
      - uses: actions/checkout@v4

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

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

      - name: Setup Node.js
        uses: actions/setup-node@v4
        with:
          node-version: '20'

      - name: Use latest npm (OIDC-ready)
        run: |
          npm install -g npm@latest
          npm --version

      - name: Build WASM
        run: npm run build

      - name: Publish to npm
        run: |
          set +e
          npm publish --access public --provenance
          EXIT_CODE=$?
          set -e

          if [ $EXIT_CODE -ne 0 ]; then
            echo ""
            echo "========================================="
            echo "=== NPM DEBUG LOG ==="
            echo "========================================="
            for log in ~/.npm/_logs/*.log; do
              echo "--- $log ---"
              cat "$log"
            done
            echo "========================================="
            echo "=== END DEBUG LOG ==="
            echo "========================================="
            echo ""

            PUBLISHED=$(npm view @npiesco/absurder-sql version 2>/dev/null || echo "")
            if [ "$PUBLISHED" = "${{ needs.validate-version.outputs.version }}" ]; then
              echo "Version ${{ needs.validate-version.outputs.version }} already published to npm, skipping"
              exit 0
            else
              exit 1
            fi
          fi

  # Create GitHub Release
  create-release:
    runs-on: ubuntu-latest
    needs: [publish-crates, publish-npm]
    permissions:
      contents: write
    steps:
      - uses: actions/checkout@v4

      - name: Create GitHub Release
        uses: softprops/action-gh-release@v1
        with:
          generate_release_notes: true
          draft: false
        env:
          GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
