name: AI PR Review

# The pull_request_target is an important feature. It is running on files from `main`.
# This is important to avoid changes which would execute code from the PR.
# See postmortem here https://github.com/Galvanized-Pukeko/gaunt-sloth-assistant/discussions/304
#
# Flow:
#   concierge       - classifies the PR author (internal vs external).
#   internal-review - runs automatically for OWNER/MEMBER/COLLABORATOR,
#                     and re-checks the association internally (defense in depth).
#   review          - runs for external contributors under the `review` environment,
#                     which has Required reviewers configured, so a maintainer must
#                     approve the deployment before the review executes.
# The two review paths share the same code via _review-shared.yml.
on:
  pull_request_target:
    types: [opened, synchronize, reopened]
    branches:
      - 'main'

jobs:
  concierge:
    runs-on: ubuntu-latest
    if: ${{ !startsWith(github.head_ref, 'dependabot') }}
    outputs:
      internal: ${{ steps.classify.outputs.internal }}
    steps:
      - name: Classify author association
        id: classify
        env:
          ASSOC: ${{ github.event.pull_request.author_association }}
        run: |
          case "$ASSOC" in
            OWNER|MEMBER|COLLABORATOR) echo "internal=true" >> "$GITHUB_OUTPUT" ;;
            *) echo "internal=false" >> "$GITHUB_OUTPUT" ;;
          esac

  internal-review:
    needs: concierge
    if: ${{ needs.concierge.outputs.internal == 'true' }}
    permissions:
      contents: read
      pull-requests: write
      issues: write
    uses: ./.github/workflows/_review-shared.yml
    with:
      environment: review-internal
      enforce_internal: true
    secrets: inherit

  review:
    needs: concierge
    if: ${{ needs.concierge.outputs.internal == 'false' }}
    permissions:
      contents: read
      pull-requests: write
      issues: write
    uses: ./.github/workflows/_review-shared.yml
    with:
      environment: review
    secrets: inherit
