name: svccat — service catalog drift check

on:
  pull_request:

# Needs write access to post PR comments.
permissions:
  pull-requests: write
  contents: read

jobs:
  svccat:
    name: Service catalog drift check
    runs-on: ubuntu-latest

    steps:
      - uses: actions/checkout@v4
        with:
          # Full history so --since can compare against the base branch.
          fetch-depth: 0

      - name: Install Rust (stable)
        uses: dtolnay/rust-toolchain@stable

      - name: Cache Cargo registry
        uses: Swatinem/rust-cache@v2

      - name: Install svccat
        run: cargo install svccat --locked

      # ── Annotate the PR diff with inline error/warning annotations ───────────
      - name: Annotate new drift (inline PR annotations)
        run: |
          svccat check \
            --since origin/${{ github.base_ref }} \
            --format github-annotation \
            || true

      # ── Post a Markdown summary as a PR comment ──────────────────────────────
      - name: Generate drift report
        id: drift
        run: |
          {
            echo 'output<<SVCCAT_EOF'
            svccat check \
              --since origin/${{ github.base_ref }} \
              --format markdown \
              || true
            echo 'SVCCAT_EOF'
          } >> "$GITHUB_OUTPUT"

      - name: Post PR comment
        uses: actions/github-script@v7
        with:
          script: |
            const output = `${{ steps.drift.outputs.output }}`;
            const marker = '<!-- svccat-drift-comment -->';
            const body = marker + '\n' + output;

            // Update existing comment if present, otherwise create a new one.
            const { data: comments } = await github.rest.issues.listComments({
              issue_number: context.issue.number,
              owner: context.repo.owner,
              repo: context.repo.repo,
            });
            const existing = comments.find(c => c.body.includes(marker));
            if (existing) {
              await github.rest.issues.updateComment({
                comment_id: existing.id,
                owner: context.repo.owner,
                repo: context.repo.repo,
                body,
              });
            } else {
              await github.rest.issues.createComment({
                issue_number: context.issue.number,
                owner: context.repo.owner,
                repo: context.repo.repo,
                body,
              });
            }

      # ── Fail the workflow if the PR introduces new drift ────────────────────
      - name: Fail on new drift
        run: |
          svccat check \
            --since origin/${{ github.base_ref }} \
            --fail-on-new-drift
