name: Test & Deploy

on:
  workflow_dispatch:
  push:
    branches:
      - master
    tags:
      - '*'
  pull_request:
    branches:
      - master

jobs:
  test:

    runs-on: ubuntu-latest

    strategy:
      matrix:
        node-version: [ '12', '14', '16' ]

    steps:
      - uses: actions/setup-node@v2
        with:
          node-version: ${{ matrix.node-version }}

      - name: Checkout
        uses: actions/checkout@v2

      - name: Audit
        run: npm audit --production

      - name: Install packages
        run: npm install

      - name: Test
        run: npm test

      - uses: actions/upload-artifact@v2
        if: failure()
        with:
          name: cypress-screenshots
          path: cypress/screenshots
          retention-days: 7

      - uses: actions/upload-artifact@v2
        if: always()
        with:
          name: cypress-videos
          path: cypress/videos
          retention-days: 7

  deploy:

    needs: [ test ]
    runs-on: ubuntu-latest
    if: github.event_name == 'push'

    steps:
      - uses: actions/setup-node@v2
        with:
          node-version: '16'

      - uses: actions/checkout@v2

      - name: Install packages
        run: npm install

      - name: Deploy @latest version to npm
        if: startsWith(github.ref, 'refs/tags/')
        uses: JS-DevTools/npm-publish@v1
        with:
          token: ${{ secrets.NPM_TOKEN }}

      - name: Update @next version
        if: startsWith(github.ref, 'refs/heads/')
        run: npm version prerelease --no-git-tag-version --preid "$GITHUB_RUN_NUMBER"

      - name: Deploy @next version to npm
        if: startsWith(github.ref, 'refs/heads/')
        uses: JS-DevTools/npm-publish@v1
        with:
          tag: next
          token: ${{ secrets.NPM_TOKEN }}
          check-version: false
