name: Auto-merge docs-only PRs

on:
  pull_request:
    branches: [main]
    types: [opened, synchronize]

jobs:
  auto-merge-docs:
    runs-on: ubuntu-latest
    steps:
      - name: Check if all changes are markdown
        id: check
        env:
          GITEA_TOKEN: ${{ secrets.AUTO_MERGE_TOKEN }}
        run: |
          PR_NUMBER=${{ github.event.pull_request.number }}
          API_URL="${{ github.server_url }}/api/v1/repos/${{ github.repository }}/pulls/${PR_NUMBER}/files"

          FILES=$(curl -sf -H "Authorization: token ${GITEA_TOKEN}" "${API_URL}" | jq -r '.[].filename')

          if [ -z "$FILES" ]; then
            echo "No files found in PR"
            echo "docs_only=false" >> "$GITHUB_OUTPUT"
            exit 0
          fi

          echo "Changed files:"
          echo "$FILES"

          DOCS_ONLY=true
          while IFS= read -r file; do
            if [[ ! "$file" =~ \.md$ ]]; then
              echo "Non-markdown file found: $file"
              DOCS_ONLY=false
              break
            fi
          done <<< "$FILES"

          echo "docs_only=${DOCS_ONLY}" >> "$GITHUB_OUTPUT"

      - name: Approve and merge
        if: steps.check.outputs.docs_only == 'true'
        env:
          GITEA_TOKEN: ${{ secrets.AUTO_MERGE_TOKEN }}
        run: |
          PR_NUMBER=${{ github.event.pull_request.number }}
          API_BASE="${{ github.server_url }}/api/v1/repos/${{ github.repository }}/pulls/${PR_NUMBER}"

          # Approve the PR
          curl -sf -X POST "${API_BASE}/reviews" \
            -H "Authorization: token ${GITEA_TOKEN}" \
            -H "Content-Type: application/json" \
            -d '{"event": "APPROVED", "body": "Auto-approved: docs-only changes (all .md files)."}'

          # Merge the PR
          curl -sf -X POST "${API_BASE}/merge" \
            -H "Authorization: token ${GITEA_TOKEN}" \
            -H "Content-Type: application/json" \
            -d '{"Do": "merge", "merge_message_field": "Auto-merge: docs-only PR #'"${PR_NUMBER}"'"}'

          echo "PR #${PR_NUMBER} auto-approved and merged."
