# 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.

# shamelessly copied from https://github.com/sigstore/cosign/blob/main/.github/workflows/milestone.yaml

name: milestone

on:
  pull_request_target:
    types: [closed]
    branches:
      - main

jobs:
  milestone:
    runs-on: ubuntu-latest

    permissions:
      actions: none
      checks: none
      contents: read
      deployments: none
      issues: write
      packages: none
      pull-requests: write
      repository-projects: none
      security-events: none
      statuses: none

    steps:
      - uses: actions/github-script@v7 # v6
        with:
          github-token: ${{ secrets.BOT_GITHUB_TOKEN }}
          script: |
            if (!context.payload.pull_request.merged) {
              console.log('PR was not merged, skipping.');
              return;
            }

            if (!!context.payload.pull_request.milestone) {
              console.log('PR has existing milestone, skipping.');
              return;
            }

            milestones = await github.rest.issues.listMilestones({
              owner: context.repo.owner,
              repo: context.repo.repo,
              state: 'open',
              sort: 'title',
              direction: 'desc'
            })

            if (milestones.data.length === 0) {
              console.log('There are no milestones, skipping.');
              return;
            }

            await github.rest.issues.update({
              owner: context.repo.owner,
              repo: context.repo.repo,
              issue_number: context.payload.pull_request.number,
              milestone: milestones.data[0].number
            });