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

env:
  NODE_VERSION: '24.15.0'

jobs:
  lighthouse:
    runs-on: ubuntu-latest

    steps:
      - uses: actions/checkout@v4

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

      - name: Install Google Chrome
        run: |
          apt-get update
          wget https://dl.google.com/linux/direct/google-chrome-stable_current_amd64.deb
          apt install -y ./google-chrome*.deb

      - name: Install global packages
        run: npm i -g pm2 @sasjs/cli wait-on

      - name: Setup and start 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
          curl -L https://github.com/sasjs/server/releases/latest/download/linux.zip > linux.zip
          unzip linux.zip
          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 \
            --output ./libraries/sheet-crypto.tgz \
            --decrypt ./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
          sasjs cbd -t server-ci

      - name: Start frontend server
        run: |
          cd client
          npx ng serve --host 0.0.0.0 --port 4200 &
          wait-on 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
