# This file contains the main workflow for the create-react-ssr project. It defines the steps and actions to be taken when the workflow is triggered.
# Name of the workflow
name: Main Workflow

# Define the events that trigger the workflow
on:
  push:
    branches: [ master ]
  pull_request:
    branches: ['*']

# Define the jobs that run as part of the workflow
jobs:
  # Job to run unit tests
  unit-front-end-testing:
    runs-on: ubuntu-latest
    steps:
    - uses: actions/checkout@v4
    - name: Use Node.js LTS
      uses: actions/setup-node@v4
      with:
        node-version: 'lts/*'
        cache: 'npm'
        registry-url: https://registry.npmjs.org/
    - run: npm ci
    - run: npm test

  # Job to run Cypress component tests
  cypress-components-testing:
    runs-on: ubuntu-latest
    steps:
      - name: Checkout
        uses: actions/checkout@v4
      # Install NPM dependencies, cache them correctly
      # and run all Cypress tests
      - name: Install dependencies
        run: npm ci
      - name: Cypress run
        uses: cypress-io/github-action@v6 # use the explicit version number
        with:
          component: true
          install: false
  
  # Job to run Cypress End to End tests
  end-to-end-testing:
    runs-on: ubuntu-latest
    env:
      PORT: 3000
      PUBLIC_URL: /
    steps:
      - name: Checkout
        uses: actions/checkout@v4
      # Install NPM dependencies, cache them correctly
      # and run all Cypress tests
      - name: Install dependencies
        run: npm ci
      - name: Cypress run
        uses: cypress-io/github-action@v6 # use the explicit version number
        with:
          install: false
          build: npm run build
          start: npm start

  # Job to build the package
  test-build-package:
    if: github.ref != 'refs/heads/master'
    needs: [ unit-front-end-testing, cypress-components-testing, end-to-end-testing ]
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
      - uses: actions/setup-node@v4
        with:
          node-version: 'lts/*'
          registry-url: https://registry.npmjs.org/
      - run: npm ci
      - run: npm run build

  # Job to publish the package to NPM
  publish-npm:
    if: github.ref == 'refs/heads/master'
    needs: [ unit-front-end-testing, cypress-components-testing, end-to-end-testing ]
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
      - uses: actions/setup-node@v4
        with:
          node-version: 'lts/*'
          registry-url: https://registry.npmjs.org/
      - run: npm ci
      - run: npm publish --access=public
        env:
          NPM_PERSONAL_TOKEN: ${{secrets.npm_token}}