name: Create GitHub Code Scanning Issues

on:
  workflow_call:
    inputs:
      artifact-name:
        description: 'Name of the artifact containing code scanning alerts'
        required: false
        type: string
        default: gh-code-scanning-alerts

permissions:
  issues: write
  actions: read

jobs:
  create-gh-code-scanning-issues:
    name: Create GitHub Code Scanning Issues
    runs-on: ubuntu-latest
    permissions:
      issues: write
      actions: read
    env:
      GH_TOKEN: ${{ github.token }}
      OWNER: ${{ github.repository_owner }}
      REPO: ${{ github.event.repository.name }}
      GITHUB_SERVER_URL: ${{ github.server_url }}
      GITHUB_REPOSITORY: ${{ github.repository }}
      GITHUB_RUN_ID: ${{ github.run_id }}
    steps:
      - name: Download alerts artifact
        uses: actions/download-artifact@3e5f45b2cfb9172054b4087a40e8e0b5a5461e7c # v8.0.1
        with:
          name: ${{ inputs.artifact-name }}

      - name: Create backlog issues for new findings
        shell: bash
        run: |
            set -euo pipefail
            while IFS= read -r alert; do
            RULE_ID=$(echo "$alert" | jq -r '.RuleId')
            RULE_DESC=$(echo "$alert" | jq -r '.RuleDescription')
            SEVERITY=$(echo "$alert" | jq -r '.SecuritySeverity // .Severity // empty')
            TOOL=$(echo "$alert" | jq -r '.Tool')
            COUNT=$(echo "$alert" | jq -r '.Count')
            HAS_FILE_PATHS=$(echo "$alert" | jq -r '.HasFilePaths')
            ALERT_URL=$(echo "$alert" | jq -r '.AlertUrl // ""')
            FINDING_DESC=$(echo "$alert" | jq -r '.FindingDescription // ""')
            MARKER="automation:security-scan:${RULE_ID}"
            if [[ -n "$SEVERITY" ]]; then
              ISSUE_TITLE="[Security][${SEVERITY}] ${RULE_DESC}"
            else
              ISSUE_TITLE="[Security] ${RULE_DESC}"
            fi
            OCCURRENCE_WORD="$([ "$COUNT" = "1" ] && echo "occurrence" || echo "occurrences")"
            DETECTION_DATE=$(date -u '+%Y-%m-%d')
            RUN_URL="${GITHUB_SERVER_URL}/${GITHUB_REPOSITORY}/actions/runs/${GITHUB_RUN_ID}"
            REPO_BASE="https://github.com/${OWNER}/${REPO}/blob/main"

            if [[ "$HAS_FILE_PATHS" == "true" ]]; then
              AFFECTED_LIST=$(echo "$alert" | jq -r --arg base "$REPO_BASE" '.AffectedPaths[] | "- [\(.)](\($base + "/" + .))"')
              PATHS_SECTION=$'### Affected paths\n\n'"${AFFECTED_LIST}"
            else
              PATHS_SECTION=$'### Repository configuration finding\n\nThis alert refers to a repository-level configuration setting with no associated source file.'
            fi

            existing=$(gh issue list \
              --repo "${OWNER}/${REPO}" \
              --search "\"${MARKER}\" in:body" \
              --state open --json number --jq '.[0].number // empty')

            ISSUE_BODY=$(cat <<EOF
            <!-- ${MARKER} -->
            ## Code Scanning Alert: ${RULE_DESC}

            **Rule:** \`${RULE_ID}\`
            $([ -n "${SEVERITY}" ] && echo "**Severity:** ${SEVERITY}")
            **Tool:** ${TOOL}
            **Occurrences:** ${COUNT} ${OCCURRENCE_WORD}
            $([ -n "${ALERT_URL}" ] && echo "**Alert:** ${ALERT_URL}")

            ### What was found
            $([ -n "${FINDING_DESC}" ] && echo "${FINDING_DESC}" || echo "See the linked alert for details.")

            ${PATHS_SECTION}

            ---
            **Detection Date:** ${DETECTION_DATE}
            **Workflow Run:** ${RUN_URL}

            ### Action Required
            - [ ] Review the alert and confirm it is not a false positive
            - [ ] Remediate or dismiss the finding with a documented reason
            - [ ] Close this issue after the fix is merged
            EOF
            )

            if [[ -z "$existing" ]]; then
              gh issue create \
                --repo "${OWNER}/${REPO}" \
                --title "${ISSUE_TITLE}" \
                --label "security,automated,needs-triage" \
                --body "${ISSUE_BODY}"
            else
              gh issue edit "${existing}" \
                --repo "${OWNER}/${REPO}" \
                --title "${ISSUE_TITLE}" \
                --body "${ISSUE_BODY}" \
                --add-label "automated,needs-triage"
              gh issue comment "${existing}" \
                --repo "${OWNER}/${REPO}" \
                --body "Weekly scan update: ${COUNT} ${OCCURRENCE_WORD} as of ${DETECTION_DATE}."
            fi
            done < <(jq -c '.[]' alerts.json)
