name: Create PR

on:
  push:
    branches-ignore:
      - main

jobs:
  create_and_enable_automerge:
    runs-on: ubuntu-latest
    steps:
      - name: Checkout repository
        uses: actions/checkout@v5

      - name: Set branch name as output
        id: branch_name
        run: echo "::set-output name=branch::${GITHUB_REF#refs/heads/}"

      - name: Create Pull Request
        id: create_pr
        uses: repo-sync/pull-request@v2
        with:
          github_token: ${{ secrets.GH_TOKEN }}
          destination_branch: 'main'
          source_branch: ''
          pr_title: '${{ steps.branch_name.outputs.branch }}'
          pr_body: |
            :magic_wand: :sparkles:

          draft: false

      - name: Assign PR to author
        if: steps.create_pr.outputs.pr_number
        run: |
          curl -s -X POST \
            -H "Authorization: token ${{ secrets.GITHUB_TOKEN }}" \
            -H "Accept: application/vnd.github.v3+json" \
            -d '{"assignees":["${{ github.actor }}"]}' \
            "https://api.github.com/repos/${{ github.repository }}/issues/${{ steps.create_pr.outputs.pr_number }}/assignees"

      - name: Get PR Node ID
        if: steps.create_pr.outputs.pr_number
        id: get_pr_id
        run: |
          PR_DATA=$(curl -s -H "Authorization: token ${{ secrets.GH_TOKEN }}" -H "Accept: application/vnd.github.v3+json" "https://api.github.com/repos/${{ github.repository }}/pulls/${{ steps.create_pr.outputs.pr_number }}")
          PR_ID=$(echo "$PR_DATA" | jq -r '.node_id')
          echo "::set-output name=node_id::$PR_ID"

      - name: Enable Auto Merge for PR
        if: steps.create_pr.outputs.pr_number
        run: |
          RESPONSE=$(curl -s -X POST \
            -H "Authorization: bearer ${{ secrets.GH_TOKEN }}" \
            -H "Content-Type: application/json" \
            -d '{
              "query": "mutation($id: ID!) { enablePullRequestAutoMerge(input: { pullRequestId: $id }) { clientMutationId } }",
              "variables": {
                "id": "'"${{ steps.get_pr_id.outputs.node_id }}"'"
              }
            }' \
            "https://api.github.com/graphql")
          echo "$RESPONSE"
          if echo "$RESPONSE" | jq -e '.errors' >/dev/null; then
            echo "Failed to enable auto merge"
            exit 1
          fi
