name: Publish to npm

on:
  push:
    branches:
      - master
  workflow_dispatch:

permissions:
  contents: write

jobs:
  publish:
    runs-on: ubuntu-latest
    timeout-minutes: 10

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

      - 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 || npm install

      - name: Check if version exists on npm
        id: version
        run: |
          PKG_NAME=$(node -p "require('./package.json').name")
          PKG_VERSION=$(node -p "require('./package.json').version")
          TAG="v${PKG_VERSION}"
          # 检查该版本是否已在 npm 上发布
          if npm view "${PKG_NAME}@${PKG_VERSION}" version 2>/dev/null; then
            echo "Version ${PKG_VERSION} already published on npm, skipping"
            echo "published=true" >> "$GITHUB_OUTPUT"
          else
            echo "Version ${PKG_VERSION} not found on npm, will publish"
            echo "published=false" >> "$GITHUB_OUTPUT"
            echo "tag=$TAG" >> "$GITHUB_OUTPUT"
          fi

      - name: Publish to npm
        if: steps.version.outputs.published == 'false'
        run: npm publish --access public
        env:
          NODE_AUTH_TOKEN: ${{ secrets.NPM_TOKEN }}

      - name: Create git tag
        if: steps.version.outputs.published == 'false'
        run: |
          TAG="${{ steps.version.outputs.tag }}"
          git config user.name "github-actions[bot]"
          git config user.email "github-actions[bot]@users.noreply.github.com"
          git tag -f "$TAG"
          git push -f origin "$TAG"
