name: Deploy

# Push su main: versione riconciliata sui tag git → lint/test/build →
# publish su npm tramite TRUSTED PUBLISHING OIDC (nessun token: GitHub
# firma ogni publish, configurato su npmjs.com → package → Trusted Publisher)
# → tag di versione.

on:
  push:
    branches: [main]

concurrency:
  group: npm-publish
  cancel-in-progress: false

permissions:
  contents: write # push del tag di versione con GITHUB_TOKEN
  id-token: write # OIDC → npm trusted publishing

jobs:
  version:
    name: Calcola versione (riconciliazione sui tag)
    runs-on: ubuntu-latest
    outputs:
      version: ${{ steps.v.outputs.version }}
    steps:
      - uses: actions/checkout@v4
        with:
          fetch-depth: 0 # serve la history dei tag
      - id: v
        run: |
          LAST=$(git tag -l "0.1.*" --sort=-v:refname | head -1 | cut -d. -f3)
          VERSION="0.1.$(( ${LAST:-0} + 1 ))"
          echo "version=${VERSION}" >> "$GITHUB_OUTPUT"
          echo "Ultimo tag 0.1.${LAST:-0} → nuova versione ${VERSION}"

  publish:
    name: Test, build & publish su npm (OIDC)
    runs-on: ubuntu-latest
    needs: version
    steps:
      - uses: actions/checkout@v4
      - uses: actions/setup-node@v4
        with:
          node-version: 22
          registry-url: 'https://registry.npmjs.org'
        # niente cache npm nei rilasci (recommendation npm per trusted publishing)
      - name: Assicura npm >= 11.5.1 (richiesto per trusted publishing OIDC)
        run: npm install -g npm@^11
      - name: Versiona il package (solo workspace, come faceva Bitbucket)
        run: npm version "${{ needs.version.outputs.version }}" --no-git-tag-version
      - run: npm ci
      - run: npm run lint
      - run: npm test
      - run: npm run build
      - name: Publish su npm (OIDC trusted publishing, nessun token)
        run: npm publish --access public

  tag-release:
    name: Tag di versione
    runs-on: ubuntu-latest
    needs: [version, publish]
    steps:
      - uses: actions/checkout@v4
      - name: Crea e pusha il tag
        env:
          VERSION: ${{ needs.version.outputs.version }}
        run: |
          git config user.name "RoBYCoNTe"
          git config user.email "2301162+RoBYCoNTe@users.noreply.github.com"
          git tag -a "${VERSION}" -m "Version ${VERSION}"
          git push origin "${VERSION}"
