name: Fix formatting

on:
  pull_request:
    types: [labeled]

permissions: {}

jobs:
  fix-formatting:
    runs-on: ubuntu-latest
    if: ${{ github.event.label.name == 'fix:formatting' }}
    permissions:
      contents: write
      pull-requests: write
    steps:
      - name: Generate a token
        id: generate-token
        uses: actions/create-github-app-token@29824e69f54612133e76f7eaac726eef6c875baf # v2.2.1
        with:
          app-id: ${{ secrets.PUSH_O_MATIC_APP_ID }}
          private-key: ${{ secrets.PUSH_O_MATIC_APP_KEY }}

      - name: 'Checkout'
        uses: actions/checkout@8e8c483db84b4bee98b60c0593521ed34d9990e8 # v6.0.1
        with:
          ref: ${{ github.event.pull_request.head.ref }}
          token: ${{ steps.generate-token.outputs.token }}
          persist-credentials: true

      - name: Setup pnpm
        uses: pnpm/action-setup@41ff72655975bd51cab0327fa583b6e92b6d3061 # v4.2.0

      - name: Setup Node
        uses: actions/setup-node@395ad3262231945c25e8478fd5baf05154b1d79f # v6.1.0
        with:
          node-version-file: './server/.nvmrc'
          cache: 'pnpm'
          cache-dependency-path: '**/pnpm-lock.yaml'

      - name: Fix formatting
        run: pnpm --recursive install && pnpm run --recursive --parallel fix:format

      - name: Commit and push
        uses: EndBug/add-and-commit@a94899bca583c204427a224a7af87c02f9b325d5 # v9.1.4
        with:
          default_author: github_actions
          message: 'chore: fix formatting'

      - name: Remove label
        uses: actions/github-script@ed597411d8f924073f98dfc5c65a23a2325f34cd # v8.0.0
        if: always()
        with:
          github-token: ${{ steps.generate-token.outputs.token }}
          script: |
            github.rest.issues.removeLabel({
              issue_number: context.payload.pull_request.number,
              owner: context.repo.owner,
              repo: context.repo.repo,
              name: 'fix:formatting'
            })
