# node-hook-action continuous integration
name: main

# Controls when the action will run. 
on:
  # Triggers the workflow on push or pull request events but only for the prod branch
  push:
    branches: [ npmjs ]
  pull_request:

  # Allows you to run this workflow manually from the Actions tab
  workflow_dispatch:

# A workflow run is made up of one or more jobs that can run sequentially or in parallel
jobs:
  # This workflow contains a single job called "build"
  build:
    # The type of runner that the job will run on
    runs-on: ubuntu-latest

    strategy:
      matrix:
        # See supported Node.js release schedule at https://nodejs.org/en/about/releases/
        node-version: [18.x]

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

      - name: Setup pnpm
        uses: pnpm/action-setup@v4
        with:
          # version from package.json
          run_install: false

      - name: Setup Node.js ${{ matrix.node-version }}
        uses: actions/setup-node@v5
        with:
          node-version: ${{ matrix.node-version }}
          cache: 'pnpm'

      - name: Install dependencies
        run: |
          echo ::group::Install dependencies
          echo "install"
          pnpm --silent install

      - name: CHECK - pnpm audit and comment on PR
        if: ${{ github.event.pull_request }}
        uses: JamesRobertWiseman/pnpm-audit@v3
        with:
          github_token: ${{ secrets.GITHUB_TOKEN }}
          level: moderate   # 'low'|'moderate'|'high'|'critical'
          fails: false # true to fail the build if vulnerabilities are found
          single_comment: true # true to only post one comment
          inline: true # true to emit audit findings directly in the workflow logs using GitHub annotation syntax

      - name: Run tests
        env:
          MT_MONGO_USER: root
          MT_MONGO_PWD: mypass
        run: pnpm test

      - name: COVERAGE - Report coverage on pull request
        if: github.event_name == 'pull_request'
        continue-on-error: true
        uses: andybelltree/lcov-reporter-action@v1.7.0 # https://github.com/andybelltree/lcov-reporter-action/releases
        with:
          lcov-file: ./coverage/lcov.info
          filter-changed-files: true

      - name: Publish NpmJS package
        if: github.ref == 'refs/heads/npmjs'
        run: |
          echo "//registry.npmjs.org/:_authToken=${{ secrets.NPM_DEPLOY_TOKEN }}" > .npmrc
          npm whoami # rely on .npmrc
          npm publish