name: Labeler

on:
  pull_request_target:
    types: [opened, synchronize, reopened]
  issues:
    types: [opened]

permissions: {}

jobs:
  label:
    permissions:
      contents: read
      pull-requests: write
    runs-on: ubuntu-latest
    steps:
      - uses: actions/create-github-app-token@d72941d797fd3113feb6b93fd0dec494b13a2547 # v1
        id: app-token
        with:
          app-id: "2729701"
          private-key: ${{ secrets.GH_APP_PRIVATE_KEY }}
      - uses: actions/labeler@8558fd74291d67161a8a78ce36a881fa63b766a9 # v5
        with:
          configuration-path: .github/labeler.yml
          repo-token: ${{ steps.app-token.outputs.token }}
          sync-labels: true
      - name: Apply maintainer label for org members
        uses: actions/github-script@f28e40c7f34bde8b3046d885e986cb6290c5673b # v7
        with:
          github-token: ${{ steps.app-token.outputs.token }}
          script: |
            const association = context.payload.pull_request?.author_association;
            if (!association) {
              return;
            }
            if (![
              "MEMBER",
              "OWNER",
            ].includes(association)) {
              return;
            }

            await github.rest.issues.addLabels({
              ...context.repo,
              issue_number: context.payload.pull_request.number,
              labels: ["maintainer"],
            });

  label-issues:
    permissions:
      issues: write
    runs-on: ubuntu-latest
    steps:
      - uses: actions/create-github-app-token@d72941d797fd3113feb6b93fd0dec494b13a2547 # v1
        id: app-token
        with:
          app-id: "2729701"
          private-key: ${{ secrets.GH_APP_PRIVATE_KEY }}
      - name: Apply maintainer label for org members
        uses: actions/github-script@f28e40c7f34bde8b3046d885e986cb6290c5673b # v7
        with:
          github-token: ${{ steps.app-token.outputs.token }}
          script: |
            const association = context.payload.issue?.author_association;
            if (!association) {
              return;
            }
            if (![
              "MEMBER",
              "OWNER",
            ].includes(association)) {
              return;
            }

            await github.rest.issues.addLabels({
              ...context.repo,
              issue_number: context.payload.issue.number,
              labels: ["maintainer"],
            });
