name: Lighthouse Checks
run-name: Running Lighthouse Performance and Accessibility Checks on Pull Request
on: [pull_request]

jobs:
  lighthouse:
    runs-on: ubuntu-latest
    strategy:
      matrix:
        node-version: [20.15.1]

    steps:
      - uses: actions/checkout@v3

      - name: Use Node.js ${{ matrix.node-version }}
        uses: actions/setup-node@v4
        with:
          node-version: ${{ matrix.node-version }}

      - name: Install Google Chrome
        run: |
          wget -q -O - https://dl-ssl.google.com/linux/linux_signing_key.pub | apt-key add -
          echo "deb http://dl.google.com/linux/chrome/deb/ stable main" > /etc/apt/sources.list.d/google.list
          apt-get update
          apt-get install -y google-chrome-stable xvfb

      - name: Install pm2 for process management
        run: npm i -g pm2

      - name: Create .env file for sasjs/server
        run: |
          touch .env
          echo RUN_TIMES=js >> .env
          echo NODE_PATH=node >> .env
          echo CORS=enable >> .env
          echo WHITELIST=http://localhost:4200 >> .env
          cat .env

      - name: Download sasjs/server package from github using curl
        run: curl -L https://github.com/sasjs/server/releases/latest/download/linux.zip > linux.zip

      - name: Unzip downloaded package
        run: unzip linux.zip

      - name: Run sasjs server
        run: pm2 start api-linux --wait-ready

      - name: Write .npmrc file
        run: echo "$NPMRC" > client/.npmrc
        shell: bash
        env:
          NPMRC: ${{ secrets.NPMRC}}

      - name: Install npm dependencies
        run: |
          cd client
          # Decrypt and Install sheet
          echo ${{ secrets.SHEET_PWD }} | gpg --batch --yes --passphrase-fd 0 ./libraries/sheet-crypto.tgz.gpg
          npm ci
          npm install -g replace-in-files-cli

      - name: Update appLoc in index.html
        run: |
          cd client
          replace-in-files --regex='appLoc=".*?"' --replacement='appLoc="/proj/sasjs/genesis-mocks"' ./src/index.html

      - name: Build Frontend
        run: |
          cd client
          npm run build

      - name: Deploy JS mocked services and frontend to the local SASjs Server instance
        run: |
          cd sas/mocks
          npm ci
          npm run deploy

      - name: Start frontend server
        run: |
          cd client
          npx ng serve --host 0.0.0.0 --port 4200 &
          npx wait-on http://localhost:4200

      - name: Wait for both servers to be ready
        run: |
          npx wait-on http://localhost:5000 http://localhost:4200

      - name: Run Lighthouse CI
        run: |
          cd client
          npx lhci autorun

      - name: Lighthouse Result Artifacts
        if: always()
        uses: actions/upload-artifact@v3
        with:
          name: Lighthouse results
          path: client/lighthouse-reports
          include-hidden-files: true