name: Close Matching Issue on PR Merge
on:
  pull_request:
    types:
      - closed
jobs:
  close_issue:
    if: github.event.pull_request.merged == true
    runs-on: ubuntu-latest
    
    steps:
      - name: Checkout target repo (main)
        uses: actions/checkout@v4
        with:
          repository: community-scripts/ProxmoxVE
          ref: main
          token: ${{ secrets.GITHUB_TOKEN }}

      - name: Extract and Process PR Title
        id: extract_title
        run: |
          title=$(echo "${{ github.event.pull_request.title }}" | sed 's/^New Script://g' | tr '[:upper:]' '[:lower:]' | sed 's/ //g' | sed 's/-//g')
          echo "Processed Title: $title"
          echo "title=$title" >> $GITHUB_ENV

      - name: Search for Issues with Similar Titles
        id: find_issue
        env:
          GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
        run: |
          issues=$(gh issue list --repo community-scripts/ProxmoxVED --json number,title --jq '.[] | {number, title}')
          
          best_match_score=0
          best_match_number=0
          
          for issue in $(echo "$issues" | jq -r '. | @base64'); do
            _jq() {
              echo ${issue} | base64 --decode | jq -r ${1}
            }

            issue_title=$(_jq '.title' | tr '[:upper:]' '[:lower:]' | sed 's/ //g' | sed 's/-//g')
            issue_number=$(_jq '.number')

            match_score=$(echo "$title" | grep -o "$issue_title" | wc -l)
            
            if [ "$match_score" -gt "$best_match_score" ]; then
              best_match_score=$match_score
              best_match_number=$issue_number
            fi
          done

          if [ "$best_match_number" != "0" ]; then
            echo "issue_number=$best_match_number" >> $GITHUB_ENV
          else
            echo "No matching issue found."
            exit 0
          fi

      - name: Comment on the Best-Matching Issue and Close It
        if: env.issue_number != ''
        env:
          GH_TOKEN: ${{ secrets.PAT_MICHEL }}
        run: |
          gh issue comment $issue_number --repo community-scripts/ProxmoxVED --body "Merged with #${{ github.event.pull_request.number }} in ProxmoxVE"
          gh issue close $issue_number --repo community-scripts/ProxmoxVED
