name: PR Changelog

permissions:
  # To add and edit comments on PRs
  contents: read
  pull-requests: write

on:
  workflow_call:
    inputs:
      ref:
        required: true
        description: "GitHub ref to use, must be the merge ref of the pull request"
        type: string
      base-ref:
        required: true
        description: "GitHub base ref, the base ref of the pull request"
        type: string
      pr-number:
        required: true
        description: "PR number to use"
        type: string
      changelog-required:
        required: true
        description: "Whether the changelog is required, used to allow check to pass on empty changelogs"
        type: boolean
    secrets:
      PULUMI_BOT_TOKEN:
        required: true
        description: "GitHub access token, required to mitigate GitHub rate limits"

defaults:
  run:
    shell: bash

jobs:
  check:
    name: comment
    runs-on: ubuntu-latest
    env:
      GITHUB_TOKEN: ${{ secrets.PULUMI_BOT_TOKEN }}
    steps:
      - uses: actions/checkout@v4
        with:
          ref: ${{ inputs.ref }}
          fetch-depth: 0
      - uses: actions/setup-go@v5
        with:
          go-version: '>=1.19.0' # decoupled from version sets, only used by changelog tool
      - name: Changelog
        id: changelog
        env:
          GITHUB_PR: ${{ inputs.pr-number }}
          PREVIOUS_VERSION: ${{ inputs.base-ref }}
          CHANGELOG_REQUIRED: ${{ inputs.changelog-required }}
        run: |
          CHANGELOG="$(./.github/scripts/get-changelog-comment "${PREVIOUS_VERSION}" "${CHANGELOG_REQUIRED}" "${GITHUB_PR}")"
          ./.github/scripts/set-output CHANGELOG "${CHANGELOG}"
      - name: Find Comment
        uses: peter-evans/find-comment@v3
        id: fc
        with:
          token: ${{ secrets.PULUMI_BOT_TOKEN }}
          issue-number: ${{ inputs.pr-number }}
          body-includes: "# Changelog"
      - name: Create or update comment
        uses: peter-evans/create-or-update-comment@v4
        with:
          token: ${{ secrets.PULUMI_BOT_TOKEN }}
          comment-id: ${{ steps.fc.outputs.comment-id }}
          issue-number: ${{ inputs.pr-number }}
          body: |
            # Changelog

            ${{ fromJSON(steps.changelog.outputs.CHANGELOG) }}
          edit-mode: replace