name: Publish to NPM

on:
  push:
    branches: [main]
  pull_request:
    branches: [main]

jobs:
  publish-to-npm:
    runs-on: ubuntu-latest

    strategy:
      matrix:
        node-version: [14.x]

    steps:
      - name: Checkout Code
        uses: actions/checkout@v4
        with:
          fetch-depth: 1

      - name: Get yarn cache
        id: yarn-cache-dir-path
        run: |
          echo "dir=$(yarn cache dir)" >> $GITHUB_OUTPUT

      - name: Cache dependencies
        uses: actions/cache@v4
        id: yarn-cache # use this to check for `cache-hit` (`steps.yarn-cache.outputs.cache-hit != 'true'`)
        with:
          path: ${{ steps.yarn-cache-dir-path.outputs.dir }}
          key: ${{ runner.os }}-yarn-${{ hashFiles('**/yarn.lock') }}
          restore-keys: |
            ${{ runner.os }}-yarn-

      - name: Set Node.js
        uses: actions/setup-node@master
        with:
          node-version: ${{ matrix.node-version }}

      - name: 'Automated Version Bump'
        uses: 'phips28/gh-action-bump-version@master'
        env:
          GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
        with:
          default: prerelease
          rc-wording: 'RELEASE,alpha,PicX'

      - name: Configure git user
        run: |
          git config --global user.email "41898282+github-actions[bot]@users.noreply.github.com"
          git config --global user.name "github-actions[bot]"

      - name: 发布npm包
        if: env.NPM_TOKEN && env.NPM_NAME
        run: |
          node index.js
          npm config set //registry.npmjs.org/:_authToken=$NPM_TOKEN
          npm publish
        env:
          NPM_TOKEN: ${{ secrets.NPM_TOKEN }}
          NPM_NAME: ${{ secrets.NPM_NAME }}