name: check-org-member

on:
  workflow_call:
    inputs:
      username:
        required: true
        type: string
    secrets:
      kilo-maintainer-app-id:
        required: true
      kilo-maintainer-app-secret:
        required: true
    outputs:
      is-member:
        description: Whether the user is an org member or kilo-maintainer bot
        value: ${{ jobs.check.outputs['is-member'] }}

jobs:
  check:
    runs-on: blacksmith-2vcpu-ubuntu-2404
    outputs:
      is-member: ${{ steps.check.outputs['is-member'] }}
    steps:
      - name: Create app token
        id: apptoken
        uses: actions/create-github-app-token@v2
        with:
          app-id: ${{ secrets['kilo-maintainer-app-id'] }}
          private-key: ${{ secrets['kilo-maintainer-app-secret'] }}
          owner: ${{ github.repository_owner }}

      - name: Check if author is org member or kilo bot
        id: check
        env:
          GITHUB_TOKEN: ${{ steps.apptoken.outputs.token }}
          USERNAME: ${{ inputs.username }}
        run: |
          if [[ "$USERNAME" == "kilo-maintainer[bot]" || "$USERNAME" == "kiloconnect[bot]" || "$USERNAME" == "kiloconnect-lite[bot]" ]]; then
            echo "is-member=true" >> "$GITHUB_OUTPUT"
            echo "User is a kilo bot"
          elif gh api orgs/Kilo-Org/members/"$USERNAME" --silent 2>/dev/null; then
            echo "is-member=true" >> "$GITHUB_OUTPUT"
            echo "User is an org member"
          else
            echo "is-member=false" >> "$GITHUB_OUTPUT"
            echo "User is not an org member"
          fi
