name: 🧽 Format checks

on:
  push:
    branches:
      - master
      - release-**
  pull_request:
    branches:
      - master
      - release-**
  issue_comment:
    types: [created]

jobs:
  pre-commit:
    runs-on: ubuntu-22.04
    steps:
      - name: Install dependencies
        run: sudo apt install -y shfmt

      - uses: actions/github-script@v7
        if: ${{ github.event.issue.pull_request }}
        id: get-pr
        with:
          script: |
            const prDetails = await github.request(context.payload.issue.pull_request.url);
            const headRef = prDetails.data.head.ref;
            const headSha = prDetails.data.head.sha;
            const headRepo = prDetails.data.head.repo.full_name;

            core.setOutput('head_ref', headRef);
            core.setOutput('head_sha', headSha);
            core.setOutput('head_repo', headRepo);

      - uses: khan/pull-request-comment-trigger@master
        id: run-fixes
        if: ${{ github.event.issue.pull_request }}
        with:
          trigger: '@qfield-fairy style please'
          reaction: rocket
        env:
          GITHUB_TOKEN: '${{ secrets.FAIRY_TOKEN }}'

      - uses: actions/checkout@v4
        if: ${{ github.event.issue.pull_request }}
        with:
          repository: ${{ steps.get-pr.outputs.head_repo }}
          ref: ${{ steps.get-pr.outputs.head_sha }} # sha

      - uses: actions/checkout@v4
        if: ${{ !github.event.issue.pull_request }}

      - name: Install Requirements
        run: |
            sudo apt install -y \
              shellcheck
            . <(curl https://aka.ms/vcpkg-init.sh -L)

      - name: Run pre-commit hooks
        uses: pre-commit/action@v3.0.1

      - name: Comment
        uses: thollander/actions-comment-pull-request@main
        if: failure() && steps.run-fixes.outputs.triggered != 'true' && github.event.issue.pull_request && !github.event.comment
        with:
          message: |
            Code formatting issues have been detected.
            Reply with `@qfield-fairy style please` to fix it up 🪄.
          GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}

      - uses: EndBug/add-and-commit@v9
        if: failure() && steps.run-fixes.outputs.triggered == 'true' && github.event.issue.pull_request
        with:
          author_name: Style Fairy
          author_email: fairy@qfield.org
          message: 'Committing style changes'
          branch: ${{ steps.get-pr.outputs.head_ref }} # branch name
        env:
          GITHUB_TOKEN: ${{ secrets.FAIRY_TOKEN }}
