name: Auto PR from Master to Develop

on:
  push:
    branches:
      - master

permissions:
  contents: write
  pull-requests: write

jobs:
  create-pr:
    runs-on: ubuntu-latest
    if: |
      !contains(github.event.head_commit.message, 'Merge pull request') &&
      !contains(github.event.head_commit.message, 'Merge branch') &&
      !startsWith(github.event.head_commit.message, 'Merge')

    steps:
      - name: Checkout repository
        uses: actions/checkout@v4
        with:
          fetch-depth: 0
          token: ${{ secrets.GITHUB_TOKEN }}

      - name: Configure Git
        run: |
          git config --global user.name "github-actions[bot]"
          git config --global user.email "github-actions[bot]@users.noreply.git.jingrow.com"

      - name: Prepare backport_master branch (Rebase)
        run: |
          git fetch origin develop
          git fetch origin master

          # Create/update backport_master from develop
          git checkout -B backport_master origin/develop

          # Rebase onto master to avoid merge commits
          git rebase origin/master || {
            echo "Rebase conflict detected, aborting."
            git rebase --abort
            exit 1
          }

          git push origin backport_master --force-with-lease

      - name: Get commit details
        run: |
          git fetch origin develop
          COMMITS=$(git log origin/develop..origin/backport_master --pretty=format:"- %h %s")
          echo "$COMMITS" > commits.txt

      - name: Check if PR already exists
        id: check-pr
        run: |
          EXISTING_PR=$(gh pr list --head backport_master --base develop --state open --json number --jq '.[0].number // empty')
          echo "existing_pr=$EXISTING_PR" >> $GITHUB_OUTPUT
        env:
          GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}

      - name: Create Pull Request
        if: steps.check-pr.outputs.existing_pr == ''
        run: |
          COMMITS_LIST=$(cat commits.txt)
          PR_DESCRIPTION="**Please perform \`Merge & Commit\` to preserve commit history**
          
          $COMMITS_LIST"

          gh pr create \
            --title "chore: Sync Changes from Master to Develop" \
            --body "$PR_DESCRIPTION" \
            --head backport_master \
            --base develop
        env:
          GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}

      - name: Update existing PR
        if: steps.check-pr.outputs.existing_pr != ''
        run: |
          COMMITS_LIST=$(cat commits.txt)
          PR_DESCRIPTION="**Please perform \`Merge & Commit\` to preserve commit history**
          
          $COMMITS_LIST"

          gh pr edit ${{ steps.check-pr.outputs.existing_pr }} \
            --body "$PR_DESCRIPTION"
        env:
          GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
