name: Create Pull Request

on:
  repository_dispatch:
    types: [create-pr]


jobs:
  Create_pull_request:
    runs-on: ubuntu-slim

    steps:
    - uses: actions/checkout@v5
      with:
        fetch-depth: 0

    - name: Clone release branch to create pull request
      run: |
        git checkout ${{ github.event.client_payload.ReleaseBranchName }}
        git branch ${{ github.event.client_payload.ReleaseBranchName }}-docs
        git push origin ${{ github.event.client_payload.ReleaseBranchName }}-docs --force

    - name: Create pull request for ${{ github.event.client_payload.ReleaseBranchName }}
      id: create-pr
      uses: actions/github-script@v8
      with:
        github-token: ${{secrets.GITHUB_TOKEN}}
        script: |
          const pulls = await github.rest.pulls.list({
            owner: context.repo.owner,
            repo: context.repo.repo,
            head: `${context.repo.owner}:${{ github.event.client_payload.ReleaseBranchName }}-docs`,
            base: "${{ github.event.client_payload.PullRequestBase }}",
            state: 'open'
          });

          if (pulls.data.length > 0) {
            console.log(`Pull request already exists: ${pulls.data[0].html_url}`);
            return pulls.data[0].number;
          } else {
            console.log('No existing pull request found, creating new one');
            let response = await github.rest.pulls.create({
              owner: context.repo.owner,
              repo: context.repo.repo,
              title: "${{ github.event.client_payload.PullRequestTitle }}",
              head: "${{ github.event.client_payload.ReleaseBranchName }}-docs",
              base: "${{ github.event.client_payload.PullRequestBase }}",
              body: `${{ github.event.client_payload.PullRequestBody }}`
            });
            return response.data.number;
          }

    - name: Request reviewers
      uses: actions/github-script@v8
      with:
        github-token: ${{secrets.PRAPPROVAL_SECRET}}
        script: |
          github.rest.pulls.requestReviewers({
              owner: context.repo.owner,
              repo: context.repo.repo,
              pull_number: ${{ steps.create-pr.outputs.result }},
              team_reviewers: ['runner-images-team']
          })