name: 'Nuxt.js Bundle Analysis'

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

defaults:
  run:
    working-directory: ./

jobs:
  analyze:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4

      - name: Set up node
        uses: actions/setup-node@v3
        with:
          node-version: '18.x'

      - name: Install dependencies
        run: yarn install

      - name: Build nuxt.js app
        run: yarn build

      # run report
      - name: Analyze bundle
        run: npx -p nuxt-bundle-analysis report

      - name: Upload bundle
        uses: actions/upload-artifact@v2
        with:
          name: bundle
          path: .nuxt/analyze/__bundle_analysis.json

      - name: Download base branch bundle stats
        uses: dawidd6/action-download-artifact@v2
        if: success() && github.event.number
        with:
          workflow: nuxt-bundle-analysis.yml
          branch: ${{ github.event.pull_request.base.ref }}
          path: .nuxt/analyze/base

      # run compare
      - name: Compare with base branch bundle
        if: success() && github.event.number
        run: ls -laR .nuxt/analyze/base &&  npx -p nuxt-bundle-analysis compare

      - name: Get comment body
        id: get-comment-body
        if: success() && github.event.number
        run: |
          if [ ! -e ".nuxt/analyze/__bundle_analysis_comment.txt" ]; then
            body="<!-- __NUXTJS_BUNDLE --> This PR introduced no changes to the javascript bundle."
          else
            body=$(cat .nuxt/analyze/__bundle_analysis_comment.txt)
            body="${body//'%'/'%25'}"
            body="${body//$'\n'/'%0A'}"
            body="${body//$'\r'/'%0D'}"
          fi
          echo ::set-output name=body::$body
      - name: Find Comment
        uses: peter-evans/find-comment@v1
        if: success() && github.event.number
        id: fc
        with:
          issue-number: ${{ github.event.number }}
          body-includes: '<!-- __NUXTJS_BUNDLE -->'

      - name: Create Comment
        uses: peter-evans/create-or-update-comment@v1.4.4
        if: success() && github.event.number && steps.fc.outputs.comment-id == 0
        with:
          issue-number: ${{ github.event.number }}
          body: ${{ steps.get-comment-body.outputs.body }}

      - name: Update Comment
        uses: peter-evans/create-or-update-comment@v1.4.4
        if: success() && github.event.number && steps.fc.outputs.comment-id != 0
        with:
          issue-number: ${{ github.event.number }}
          body: ${{ steps.get-comment-body.outputs.body }}
          comment-id: ${{ steps.fc.outputs.comment-id }}
          edit-mode: replace
