name: Changelog Check

on:
  pull_request:
    types: [opened, synchronize, labeled, unlabeled]

jobs:
  check-changelog:
    runs-on: ubuntu-latest
    steps:
      - name: Checkout code
        uses: actions/checkout@08c6903cd8c0fde910a37f88322edcfb5dd907a8 # v5

      - name: Check if changelog should be skipped
        id: check-label
        run: |
          LABELS=$(gh pr view ${{ github.event.pull_request.number }} --json labels --jq '.labels[].name')

          # "grep -w" to check for the whole words
          if echo "$LABELS" | grep -w -qE "(changelog-not-needed|dependency-update|vendored-mimir-prometheus-update|helm-weekly-release|backport)"; then
            echo "skip=true" >> $GITHUB_OUTPUT
            echo "PR has a label that skips changelog check, skipping changelog check"
          else
            echo "skip=false" >> $GITHUB_OUTPUT
            echo "PR does not have any labels that skip changelog check, will check changelog"
          fi
        env:
          GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}

      - name: Check PR reference in CHANGELOG.md
        if: steps.check-label.outputs.skip == 'false'
        run: |
          PR_NUMBER=${{ github.event.pull_request.number }}
          MAIN_CHANGELOG_FOUND=false
          HELM_CHANGELOG_FOUND=false
          
          if grep -q "#${PR_NUMBER}" CHANGELOG.md; then
            echo "✅ PR #${PR_NUMBER} is referenced in CHANGELOG.md"
            MAIN_CHANGELOG_FOUND=true
          fi
          
          if grep -q "#${PR_NUMBER}" operations/helm/charts/mimir-distributed/CHANGELOG.md; then
            echo "✅ PR #${PR_NUMBER} is referenced in helm CHANGELOG.md"
            HELM_CHANGELOG_FOUND=true
          fi
          
          if [ "$MAIN_CHANGELOG_FOUND" = true ] || [ "$HELM_CHANGELOG_FOUND" = true ]; then
            echo "✅ PR #${PR_NUMBER} is referenced in at least one changelog"
          else
            echo "❌ PR #${PR_NUMBER} is not referenced in CHANGELOG.md or operations/helm/charts/mimir-distributed/CHANGELOG.md"
            echo "Please add an entry for this PR in the appropriate changelog or add one of these labels if this change doesn't require a changelog entry: 'changelog-not-needed', 'dependency-update', 'vendored-mimir-prometheus-update', 'helm-weekly-release'"
            exit 1
          fi
