name: Unlighthouse

on:
  push:
    branches: main
  pull_request:

permissions:
  pull-requests: write

jobs:
  unlighthouse:
    runs-on: ubuntu-latest
    env:
      COMMENT_ID: unlighthouse-node${{matrix.node-version}}
      PORT: 8000
      CLOUDFLARE_PROJECT: omnidash-unlighthouse
      WEBSITE_URL: https://omnidash.io
      BADGE_FILE: omnidash.io-unlighthouse.json
      BADGE_GIST: b948b29508e19955106a1037d2a615e6
    strategy:
      matrix:
        node-version: [20]
    steps:
      - name: Create initial comment
        uses: marocchino/sticky-pull-request-comment@v2.9.0
        if: github.ref != 'refs/heads/main'
        with:
          header: ${{ env.COMMENT_ID }}
          message: |
            ## 🔄 **Unlighthouse report in progress** 🗼

            <div align="center"></br></br><img src="https://github.com/bartvdbraak/omnidash/assets/3996360/f994f62a-6a85-450b-bb4d-927a56542e33"></div>

      - name: Set variables based on trigger
        id: set_variables
        run: |
          if [[ ${{ github.ref == 'refs/heads/main' }} == true ]]; then
            echo "CLOUDFLARE_BRANCH=main" >> $GITHUB_OUTPUT
            echo "CLOUDFLARE_URL=https://${{ env.CLOUDFLARE_PROJECT }}.pages.dev" >> $GITHUB_OUTPUT
          else
            echo "CLOUDFLARE_BRANCH=pull-${{ github.event.pull_request.number }}" >> $GITHUB_OUTPUT
            echo "CLOUDFLARE_URL=https://pull-${{ github.event.pull_request.number }}.${{ env.CLOUDFLARE_PROJECT }}.pages.dev" >> $GITHUB_OUTPUT
          fi

      - name: Checkout repository
        uses: actions/checkout@v4.1.2

      - name: Setup pnpm
        uses: pnpm/action-setup@v3.0.0
        with:
          version: latest

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

      - name: Retrieve Vercel Preview URL
        uses: zentered/vercel-preview-url@v1.1.9
        id: vercel_preview_url
        env:
          VERCEL_TOKEN: ${{ secrets.VERCEL_TOKEN }}
        with:
          vercel_project_id: ${{ vars.VERCEL_PROJECT_ID }}

      - name: Await Vercel Deployment
        uses: UnlyEd/github-action-await-vercel@v1.2.43
        env:
          VERCEL_TOKEN: ${{ secrets.VERCEL_TOKEN }}
        with:
          deployment-url: ${{ steps.vercel_preview_url.outputs.preview_url }}
          timeout: 360

      - name: Install Dependencies
        run: pnpm install

      - name: Run Unlighthouse
        run: |
          export SCAN_URL="${{ github.ref == 'refs/heads/main' && env.WEBSITE_URL || steps.vercel_preview_url.outputs.preview_url }}"
          export AUTH_COOKIE="$(curl "https://$SCAN_URL/auth?/login" -H "Origin: https://$SCAN_URL" -F "usernameEmail=test_user" -F "password=${{ secrets.TEST_USER_PASSWORD }}" --verbose 2>&1 | awk -F'pb_auth=' '/pb_auth/{print $2;exit}' | awk -F';' '{print $1}')"

          pnpm run unlighthouse

      - name: Upload report to Cloudflare pages
        uses: cloudflare/wrangler-action@v3.4.1
        with:
          apiToken: ${{ secrets.CLOUDFLARE_API_TOKEN }}
          command: pages deploy .unlighthouse --project-name="${{ env.CLOUDFLARE_PROJECT }}" --branch=${{ steps.set_variables.outputs.CLOUDFLARE_BRANCH }}

      - name: Create comment content
        id: create_comment
        uses: actions/github-script@v7.0.1
        with:
          github-token: ${{ secrets.GITHUB_TOKEN }}
          result-encoding: string
          script: |
            const fs = require('fs');
            const result = JSON.parse(fs.readFileSync('.unlighthouse/ci-result.json', 'utf8'));
            const formatScore = score => `${Math.round(score * 100)} (${score})`;
            const getEmoji = score => score >= 0.9 ? '🟢' : score >= 0.5 ? '🟠' : '🔴';
            const getColor = score => score >= 0.9 ? '4c1' : score >= 0.5 ? 'ffa400' : 'eb0f00';
            const score = res => `${getEmoji(res)} ${formatScore(res)}`;
            const reportUrl = `${{ steps.set_variables.outputs.CLOUDFLARE_URL }}`;
            return [
                `## ✅ **Unlighthouse report** 🗼`,
                '| Category | Score |',
                '| --- | --- |',
                `| Performance | ${score(result.summary.categories.performance.averageScore)} |`,
                `| Accessibility | ${score(result.summary.categories.accessibility.averageScore)} |`,
                `| Best practices | ${score(result.summary.categories['best-practices'].averageScore)} |`,
                `| SEO | ${score(result.summary.categories.seo.averageScore)} |`,
                `| *Overall* | ${score(result.summary.score)} |`,
                '',
                '*Lighthouse scores for individual routes:*',
                '',
                '| Path | Performance | Accessibility | Best practices | SEO | Overall |',
                '| --- | --- | --- | --- | --- | --- |',
                `${result.routes.map(route => `| ${route.path} | ${score(route.categories.performance.score)} | ${score(route.categories.accessibility.score)} | ${score(route.categories['best-practices'].score)} | ${score(route.categories.seo.score)} | ${score(route.score)} |`).join('\n')}`,
                '',
                '*Lighthouse metrics:*',
                '',
                '| Metric | Average Value |',
                '| --- | --- |',
                `${Object.entries(result.summary.metrics).map(([metric, { averageNumericValue }]) => `| ${metric} | ${averageNumericValue} |`).join('\n')}`,
                '',
                `View the full Lighthouse report [here](${reportUrl}).`,
            ].join('\n');

      - name: Create summary score
        id: create_score
        uses: actions/github-script@v7.0.1
        with:
          github-token: ${{ secrets.GITHUB_TOKEN }}
          result-encoding: string
          script: |
            const fs = require('fs');
            const result = JSON.parse(fs.readFileSync('.unlighthouse/ci-result.json', 'utf8'));
            return `${Math.round(result.summary.score * 100)}`;

      - name: Create summary score color
        id: create_score_color
        uses: actions/github-script@v7.0.1
        with:
          github-token: ${{ secrets.GITHUB_TOKEN }}
          result-encoding: string
          script: |
            const fs = require('fs');
            const result = JSON.parse(fs.readFileSync('.unlighthouse/ci-result.json', 'utf8'));
            const getColor = score => score >= 0.9 ? '4c1' : score >= 0.5 ? 'ffa400' : 'eb0f00';
            return getColor(result.summary.score);

      - name: Update comment with result
        uses: marocchino/sticky-pull-request-comment@v2.9.0
        if: github.ref != 'refs/heads/main'
        with:
          header: ${{ env.COMMENT_ID }}
          message: ${{ steps.create_comment.outputs.result }}

      - name: Create Lighthouse Score badge
        uses: schneegans/dynamic-badges-action@v1.7.0
        if: github.ref == 'refs/heads/main'
        with:
          auth: ${{ secrets.GIST_SECRET }}
          gistID: ${{ env.BADGE_GIST }}
          filename: ${{ env.BADGE_FILE }}
          namedLogo: Lighthouse
          label: lighthouse
          message: ${{ steps.create_score.outputs.result }}
          color: ${{ steps.create_score_color.outputs.result }}

      - name: Update comment on failure
        uses: marocchino/sticky-pull-request-comment@v2.9.0
        if: failure() && github.ref != 'refs/heads/main'
        with:
          header: ${{ env.COMMENT_ID }}
          message: |
            ## ❌ **Unlighthouse report failed** 🗼

            <div align="center"></br></br><img src="https://github.com/bartvdbraak/omnidash/assets/3996360/cc1c6fb9-f9be-4a69-9666-655d6733abeb"></div>

      - name: Update comment on cancel
        uses: marocchino/sticky-pull-request-comment@v2.9.0
        if: cancelled() && github.ref != 'refs/heads/main'
        with:
          header: ${{ env.COMMENT_ID }}
          message: |
            ## 🛑 **Unlighthouse report was cancelled** 🗼

            <div align="center"></br></br><img src="https://github.com/bartvdbraak/omnidash/assets/3996360/cc1c6fb9-f9be-4a69-9666-655d6733abeb"></div>