name: "🚀 publish"

on:
    push:
        branches:
          - main

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

jobs:
    release:
        name: 🚀 publish
        runs-on: ubuntu-latest
        steps:
            - name: 📚 checkout
              uses: actions/checkout@v6

            - name: 🟢 node
              uses: actions/setup-node@v6
              with:
                  node-version: 24
                  registry-url: https://registry.npmjs.org

            # --- Pack & sign with Unity's official Package Manager CLI ---
            # https://docs.unity3d.com/6000.3/Documentation/Manual/upm-cli.html
            # Service account must hold the "Package Manager Package Signer" role.
            - name: 🔏 pack & sign unity package
              env:
                UPM_SERVICE_ACCOUNT_KEY_ID: ${{ secrets.UPM_SERVICE_ACCOUNT_KEY_ID }}
                UPM_SERVICE_ACCOUNT_KEY_SECRET: ${{ secrets.UPM_SERVICE_ACCOUNT_KEY_SECRET }}
                UNITY_ORGANIZATION_ID: ${{ secrets.UNITY_ORG_ID }}
              run: |
                set -euo pipefail

                # Install the official UPM CLI (adds `upm` to PATH via shell profile,
                # which a non-interactive CI shell does NOT pick up — so resolve the
                # binary directly below).
                curl -fsSL https://cdn.packages.unity.com/upm-cli/install.sh | bash

                UPM_BIN="$(command -v upm || true)"
                if [ -z "${UPM_BIN}" ]; then
                  UPM_BIN="$(find "${HOME}" -type f -name upm 2>/dev/null | head -n1)"
                fi
                if [ -z "${UPM_BIN}" ]; then
                  echo "::error::Could not locate the 'upm' binary after install." >&2
                  exit 1
                fi

                "${UPM_BIN}" --version

                # Packs the package in the repo root and writes the SIGNED tarball to ./dist
                "${UPM_BIN}" pack . --organization-id "${UNITY_ORGANIZATION_ID}" --destination ./dist

            # --- Publish the SIGNED tarball (do NOT let npm repack the source) ---
            - name: 🚀 publish
              run: |
                set -euo pipefail
                TARBALL="$(ls ./dist/*.tgz | head -n1)"
                echo "Publishing ${TARBALL}"
                npm publish "${TARBALL}" --access public --provenance