name: Publish to NPM

on:
  push:
    branches:
      - "[0-9]+.[0-9]+"
  workflow_dispatch:
    inputs:
      ref:
        description: "Tag or branch to publish from"
        required: true
        type: string
        default: "main"

permissions:
  contents: write
  id-token: write

jobs:
  publish:
    runs-on: ubuntu-latest
    environment: publish

    steps:
      - name: Checkout code
        uses: actions/checkout@v4
        with:
          ref: ${{ github.event.inputs.ref || github.ref }}

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

      - name: Install dependencies
        run: npm ci

      - name: Build project
        run: npm run build-pretty

      - name: Get version from package.json
        id: get_version
        run: echo "version=$(node -p "require('./package.json').version")" >> $GITHUB_OUTPUT

      - name: Create and push git tag
        run: |
          git config --local user.email "action@github.com"
          git config --local user.name "GitHub Action"
          git tag v${{ steps.get_version.outputs.version }}
          git push origin v${{ steps.get_version.outputs.version }}

      - name: Publish to NPM
        run: |
          npm publish --tag latest --access public
        env:
          NODE_AUTH_TOKEN: ${{ secrets.NPM_TOKEN }}
      - name: Merge to main branch
        run: |
          git config --local user.email "action@github.com"
          git config --local user.name "GitHub Action"
          git fetch origin main
          git checkout main
          git checkout -B main origin/main
          git merge ${{ github.ref_name }} --no-ff -m "Merge ${{ github.ref_name }} into main after release v${{ steps.get_version.outputs.version }}"
          git push origin main
