name: End-to-End Tests

on:
  push:
    branches:
      - main
  pull_request:
    branches:
      - main

jobs:
  build:
    name: Build
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v3

      - uses: actions/setup-node@v3
        with:
          node-version: 14
          registry-url: https://registry.npmjs.org
          cache: 'yarn'

      - uses: actions/cache@v3
        id: install-cache
        with:
          path: node_modules/
          key: ${{ runner.os }}-install-${{ hashFiles('**/yarn.lock') }}

      - if: steps.install-cache.outputs.cache-hit != 'true'
        run: yarn install --frozen-lockfile --ignore-scripts

      - run: yarn prepare

      - run: yarn build

      - uses: actions/upload-artifact@v2
        with:
          name: build
          path: build
          if-no-files-found: error

      - uses: actions/cache@v3
        id: cypress-cache
        with:
          path: /home/runner/.cache/Cypress
          key: ${{ runner.os }}-cypress-${{ hashFiles('node_modules/cypress') }}

      - if: steps.cypress-cache.outputs.cache-hit != 'true'
        run: yarn cypress install

  cypress-tests:
    name: Run tests
    runs-on: ubuntu-latest
    needs: build
    strategy:
      fail-fast: false
      matrix:
        containers: [1, 2, 3, 4]
    steps:
      - uses: actions/checkout@v3

      - uses: actions/setup-node@v3
        with:
          node-version: 14
          registry-url: https://registry.npmjs.org
          cache: 'yarn'

      - uses: actions/cache@v3
        id: install-cache
        with:
          path: node_modules/ # this should always be a cache hit, from install
          key: ${{ runner.os }}-install-${{ hashFiles('**/yarn.lock') }}

      - if: steps.install-cache.outputs.cache-hit != 'true'
        run: yarn install --frozen-lockfile --ignore-scripts

      - uses: actions/download-artifact@v2
        with:
          name: build
          path: build

      - uses: actions/cache@v3
        id: cypress-cache
        with:
          path: /home/runner/.cache/Cypress
          key: ${{ runner.os }}-cypress-${{ hashFiles('node_modules/cypress') }}

      - if: steps.cypress-cache.outputs.cache-hit != 'true'
        run: yarn cypress install

      - uses: cypress-io/github-action@v4
        with:
          install: false
          start: yarn serve
          wait-on: 'http://localhost:3000'
          browser: chrome
          record: true
          parallel: true
        env:
          CI: false # disables lint checks when building
          CYPRESS_RECORD_KEY: ${{ secrets.CYPRESS_RECORD_KEY }}
          GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
