name: "Release Manager: sync changelog with PR"

on:
  push:
    branches:
      - develop
    paths:
      - 'CHANGELOG.md'

env:
  GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}

permissions:
  contents: write
  issues: write
  pull-requests: write

jobs:
  edit:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
      # headが$GITHUB_REF_NAME, baseが$STABLE_BRANCHかつopenのPRを1つ取得
      - name: Get PR
        run: |
          echo "pr_number=$(gh pr list --limit 1 --search "head:$GITHUB_REF_NAME base:$STABLE_BRANCH is:open" --json number  --jq '.[] | .number')" >> $GITHUB_OUTPUT
        id: get_pr
        env:
          STABLE_BRANCH: ${{ vars.STABLE_BRANCH }}
      - name: Get target version
        if: steps.get_pr.outputs.pr_number != ''
        uses: misskey-dev/release-manager-actions/.github/actions/get-target-version@v2
        id: v
      # CHANGELOG.mdの内容を取得
      - name: Get changelog
        if: steps.get_pr.outputs.pr_number != ''
        uses: misskey-dev/release-manager-actions/.github/actions/get-changelog@v2
        with:
          version: ${{ steps.v.outputs.target_version }}
        id: changelog
      # PRのnotesを更新
      - name: Update PR
        if: steps.get_pr.outputs.pr_number != ''
        run: |
          gh pr edit "$PR_NUMBER" --body "$CHANGELOG"
        env:
          PR_NUMBER: ${{ steps.get_pr.outputs.pr_number }}
          CHANGELOG: ${{ steps.changelog.outputs.changelog }}
