# This workflow will run tests using node and then publish a package to GitHub Packages when a release is created
# For more information see: https://help.github.com/actions/language-and-framework-guides/publishing-nodejs-packages

name: npm Publish Package

on:
  pull_request:
    types:
      - closed
    branches:
      - master

jobs:
  build:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v3
      - uses: actions/setup-node@v3
        with:
          node-version: 16
      - run: npm ci
      - run: npm run compile
      - run: npm test
      - run: npm run dist

  publish-npm:
    needs: build
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v3
      - uses: actions/setup-node@v3
        with:
          node-version: 16
          registry-url: https://registry.npmjs.org/

      - name: Check if tag is a version
        id: check_version
        run: |
          git fetch --tags
          VERSION_TAG=$(git tag --list --sort=-version:refname "v*" | head -n 1)
          echo "Version: $VERSION_TAG"
          LAST_VER=v$(npm view js-big-decimal version)
          echo "Published Version: $LAST_VER"
          if [[ "$VERSION_TAG" != "$LAST_VER" ]]; then
            echo "is_version=true" >> $GITHUB_ENV
          else
            echo "is_version=false" >> $GITHUB_ENV
          fi

      - name: Debug env
        run: |
          echo "is_version: ${{env.is_version}}"
      - name: Publish
        if: env.is_version == 'true'
        run: |
          npm ci
          npm publish
        env:
          NODE_AUTH_TOKEN: ${{secrets.npm_token}}
