# Copyright © 2023 OpenIM. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

name: Github Rebot for Cherry Pick when PR is merged
on:
  pull_request_target:
    types:
      - closed

jobs:
  comment:
    runs-on: ubuntu-latest
    steps:
      - name: Comment cherry-pick command
        uses: actions/github-script@v7
        with:
          github-token: ${{ secrets.BOT_GITHUB_TOKEN }}
          script: |
            const pr = context.payload.pull_request;
            if (!pr.merged) {
              console.log("PR is not merged. Skipping...");
              return;
            }
            if (!pr.milestone || !pr.milestone.title) {
              console.log("Milestone is not set. Skipping...");
              return;
            }
            const milestone = pr.milestone.title;
            const ref = `heads/release-${milestone}`;
            let branchExists;
            try {
              await github.rest.git.getRef({
                owner: context.repo.owner,
                repo: context.repo.repo,
                ref: ref
              });
              branchExists = true;
            } catch (error) {
              if (error.status === 404) {
                console.log(`Branch ${ref} does not exist. Skipping...`);
                branchExists = false;
              } else {
                throw error; // Rethrow if it's another error
              }
            }
            if (!branchExists) {
              return;
            }
            const cherryPickCmd = `/cherry-pick release-${milestone}`;
            console.log(`Adding comment: ${cherryPickCmd}`);
            await github.rest.issues.createComment({
              owner: context.repo.owner,
              repo: context.repo.repo,
              issue_number: pr.number,
              body: cherryPickCmd
            });