name: Unlighthouse SEO Reports

on:
  deployment_status

permissions:
  contents: read
  pages: write
  id-token: write

concurrency:
  group: "pages"
  cancel-in-progress: false

jobs:
  build-deploy:

    if: github.event.deployment_status.state == 'success'  && (github.event.deployment_status.environment == 'Production' || github.event.deployment_status.environment == 'Preview')

    environment:
      name: github-pages
      url: https://${{ github.repository_owner }}.github.io/${{ github.event.repository.name }}/${{ steps.git-branch.outputs.SOURCE_REF }}

    runs-on: ubuntu-latest
    steps:
      - name: Check out
        uses: actions/checkout@v3

      - name: Set up Node.js
        uses: actions/setup-node@v3
        with:
          node-version: 20

      - name: Install Dependencies
        run: yarn global add @unlighthouse/cli puppeteer

      - name: Get Deployment Source Branch Name
        id: git-branch
        run: |
           git fetch --all
           git branch -a --contains ${{ github.event.deployment.ref }}
           source_branches="$(git branch -a --contains ${{ github.event.deployment.ref }})"
           result=$(echo "$source_branches" | tail -n1 | sed 's/^[ \t]*//')
           echo "Remote source of deployment: ${result}"
           echo "Local git ref of deployment: ${result#remotes/origin/*}"
           echo "SOURCE_REF=${result#remotes/origin/*}" >> "$GITHUB_OUTPUT"

      - name: Build Unlighthouse report
        run: |
          unlighthouse-ci \
            --site "${{ github.event.deployment_status.target_url }}" \
            --build-static \
            --router-prefix "${{ github.event.repository.name }}/${{ steps.git-branch.outputs.SOURCE_REF }}"

      - name: Deploy
        uses: peaceiris/actions-gh-pages@v3
        with:
          deploy_key: ${{ secrets.GH_PAGES_DEPLOY_PRIVATE_KEY }}
          publish_dir: ./.unlighthouse
          destination_dir: ${{ steps.git-branch.outputs.SOURCE_REF }}

      - name: Calculate Average Score
        id: calculate-score
        run: |
          average=$(jq -r '[.[] | .score] | add / length' ./.unlighthouse/ci-result.json)
          echo "average_score=${average}" >> "$GITHUB_OUTPUT"

      - name: Create Markdown Table
        id: create-table
        env:
          md_file_path: './.unlighthouse/table.md'
        run: |
          echo "## Unlighthouse Results" > $md_file_path
          echo "" >> $md_file_path
          echo "Overall score: **${{ steps.calculate-score.outputs.average_score }}**" >> $md_file_path
          echo "" >> $md_file_path
          echo "Path | Score" >> $md_file_path
          echo "-----|------" >> $md_file_path
          cat ./.unlighthouse/ci-result.json | jq -r '.[] | [.path, .score] | @tsv' | sed 's/\t/ | /g' >> $md_file_path
          echo "" >> $md_file_path
          echo "[View the full report](https://${{ github.repository_owner }}.github.io/${{ github.event.repository.name }}/${{ steps.git-branch.outputs.SOURCE_REF }})" >> $md_file_path
          echo "md_file_path=${md_file_path}" >> "$GITHUB_OUTPUT"

      - run: |
          echo GITHUB_ACTION: $GITHUB_ACTION
          echo GITHUB_WORKFLOW: $GITHUB_WORKFLOW
          echo GITHUB_EVENT_NAME: $GITHUB_EVENT_NAME
          echo GITHUB_EVENT_PATH: $GITHUB_EVENT_PATH
          cat $GITHUB_EVENT_PATH

      - name: Comment on Pull Request
        uses: actions/github-script@v6
        with:
          script: |
            const fs = require('fs');
            const tablePath = fs.readFileSync('${{ steps.create-table.outputs.md_file_path }}', 'utf8');
            github.rest.issues.createComment({
              issue_number: context.issue.number,
              owner: context.repo.owner,
              repo: context.repo.repo,
              body: tablePath
            });

      - name: Comment on issue
        id: create_comment
        uses: actions/github-script@v6
        with:
          github-token: ${{secrets.GH_PAGES_TOKEN}}
          script: |
            const fs = require('fs');
            const tablePath = fs.readFileSync('${{ steps.create-table.outputs.table_path }}', 'utf8');

            github.rest.issues.createComment({
              issue_number: context.issue.number,
              owner: context.repo.owner,
              repo: context.repo.repo,
              body: tablePath
            })