name: Continuous Release

on:
  workflow_dispatch:
  push:
    branches:
      - main

# OIDC token for npm Trusted Publishers (no NPM_TOKEN secret needed).
# contents: write is required for the version-bump commit and release creation.
permissions:
  id-token: write  # Required for npm OIDC Trusted Publishing
  contents: write  # Required for version bump commit + GitHub release

jobs:
  # https://github.com/marketplace/actions/automated-version-bump
  bump-version:
    name: Bump Version & Create GitHub Tag
    runs-on: ubuntu-latest
    outputs:
      new-version: ${{ steps.version-bump.outputs.newTag }}

    steps:
      - name: Checkout code
        uses: actions/checkout@v4

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

      # Wording ONLY looks at the commit message, not the PR title
      # Settings > pull requests > allow merge commits > default to pull request title
      - name: Automated Version Bump
        id: version-bump
        uses: phips28/gh-action-bump-version@master
        env:
          GITHUB_TOKEN: ${{ github.token }}
        with:
          commit-message: "CI: bumps version to {{version}} [skip ci]"
          major-wording: "MAJOR"
          minor-wording: "MINOR"
          target-branch: "main"

  # https://github.com/ncipollo/release-action
  create-release:
    name: Create GitHub Release
    runs-on: ubuntu-latest
    needs: [bump-version]
    if: needs.bump-version.outputs.new-version != ''

    steps:
      - name: Checkout code
        uses: actions/checkout@v4
        with:
          fetch-depth: 0  # necessary to get newly created tag above
          ref: 'main'

      - name: New Version
        env:
          NEW_VERSION: ${{ steps.bump-version.outputs.new-version }}
        run: echo "new version $NEW_VERSION"

      - name: Create tag and release
        uses: ncipollo/release-action@v1
        with:
          commit: 'main'
          name: ${{ needs.bump-version.outputs.new-version }}
          tag: ${{ needs.bump-version.outputs.new-version }}

  # https://github.com/marketplace/actions/npm-publish
  npm-publish:
    name: Publish to npm (OIDC Trusted Publisher)
    runs-on: ubuntu-latest
    needs: [bump-version, create-release]
    if: needs.bump-version.outputs.new-version != ''

    steps:
      - name: Checkout code
        uses: actions/checkout@v4
        with:
          fetch-depth: 0
          ref: 'main'

      # registry-url wires the OIDC token into .npmrc automatically —
      # no NPM_TOKEN secret required.
      - name: Setup Node.js
        uses: actions/setup-node@v4
        with:
          node-version: 20
          registry-url: 'https://registry.npmjs.org'

      - name: Update npm (≥ 11.5.1 required for OIDC)
        run: npm install -g npm@latest

      - name: Publish to npm
        run: npm publish --access public
