name: "Apply issue labels to PR"

on:
  pull_request_target:
    types:
      - opened

permissions:
  contents: read

jobs:
  label_on_pr:
    runs-on: ubuntu-latest

    permissions:
      contents: none
      issues: read
      pull-requests: write

    steps:
      - name: Harden the runner (Audit all outbound calls)
        uses: step-security/harden-runner@0634a2670c59f64b4a01f0f96f84700a4088b9f0 # v2.12.0
        with:
          egress-policy: audit

      - name: Apply labels from linked issue to PR
        uses: actions/github-script@60a0d83039c74a4aee543508d2ffcb1c3799cdea # v7.0.1
        with:
          github-token: ${{ secrets.GITHUB_TOKEN }}
          script: |
            async function getLinkedIssues(owner, repo, prNumber) {
              const query = `query GetLinkedIssues($owner: String!, $repo: String!, $prNumber: Int!) {
                repository(owner: $owner, name: $repo) {
                  pullRequest(number: $prNumber) {
                    closingIssuesReferences(first: 10) {
                      nodes {
                        number
                        labels(first: 10) {
                          nodes {
                            name
                          }
                        }
                      }
                    }
                  }
                }
              }`;

              const variables = {
                owner: owner,
                repo: repo,
                prNumber: prNumber,
              };

              const result = await github.graphql(query, variables);
              return result.repository.pullRequest.closingIssuesReferences.nodes;
            }

            const pr = context.payload.pull_request;
            const linkedIssues = await getLinkedIssues(
              context.repo.owner,
              context.repo.repo,
              pr.number
            );

            const labelsToAdd = new Set();
            for (const issue of linkedIssues) {
              if (issue.labels && issue.labels.nodes) {
                for (const label of issue.labels.nodes) {
                  labelsToAdd.add(label.name);
                }
              }
            }

            if (labelsToAdd.size) {
              await github.rest.issues.addLabels({
                owner: context.repo.owner,
                repo: context.repo.repo,
                issue_number: pr.number,
                labels: Array.from(labelsToAdd),
              });
            }
