name: Gitflow Hotfix PR Create
description: 'On hotfix branch create, base branch pull request create'

inputs:
  base:
    description: target branch
    default: dev
    required: false
  pat:
    description: Github Personal Access Token
    default: ''
    required: true
  dummycommit:
    description: dummy commit
    default: 'no'
    required: false

runs:
  using: "composite"
  steps:
    - name: gh auth login
      shell: bash
      run: |
        echo ${{ env.PAT }} | gh auth login --with-token
      env:
        PAT: ${{ inputs.pat }}

    - name: branch check
      id: check
      shell: bash
      run: |
        origin_branch_name=${{ github.ref }}
        branch_name=${origin_branch_name#refs/heads/}
        
        echo "origin current branch: ${{ github.ref }}"
        echo "current branch: $branch_name"
        echo "branch_name=$branch_name" >> $GITHUB_OUTPUT
        
        echo "dummy commit=${{ inputs.dummycommit }}"
        dummy=${{ inputs.dummycommit }}
        echo "dummy_commit=$dummy" >> $GITHUB_OUTPUT

    - name: Check if PR already exists
      id: check_pr_exist
      shell: bash
      run: |
        pr_list=$(gh pr list -s open -H ${{ steps.check.outputs.branch_name }} -B ${{ inputs.base }} --json headRefName | jq -r '.[].headRefName' | head -n 1)
        if [ -n "$pr_list" ]; then
          echo "current pr exist: true"
          echo "exist=true" >> $GITHUB_OUTPUT
        else
          echo "current pr exist: false"
          echo "exist=false" >> $GITHUB_OUTPUT
        fi

    - name: Add dummy commit
      if: ${{ steps.check_pr_exist.outputs.exist == 'false' && steps.check.outputs.dummy_commit == 'yes' }}
      shell: bash
      run: |
        git config --local user.email "github-actions[bot]@users.noreply.github.com"
        git config --local user.name "github-actions[bot]"
        git commit -m "automatically pr create" --allow-empty
        git push origin ${{ steps.check.outputs.branch_name }}

    - name: create pull request
      if: ${{ steps.check_pr_exist.outputs.exist == 'false' }}
      shell: bash
      run: |
        echo "Create PR for ${{ steps.check.outputs.branch_name }} to ${{ inputs.base }} branch."
        gh pr create --base ${{ inputs.base }} --title "[Gitflow] Auto Create PR from ${{ steps.check.outputs.branch_name }} to ${{ inputs.base }}" \
          --body "This PR is automatically created by CI to merge ${{ steps.check.outputs.branch_name }} branch into ${{ inputs.base }} branch."
      env:
        GITHUB_TOKEN: ${{ inputs.pat }}
