name: Update Issue on PR Merge

on:
  pull_request:
    types: [closed]
    branches:
      - main

permissions:
  issues: write
  pull-requests: read

jobs:
  update_issues:
    if: github.event.pull_request.merged == true && github.repository == 'community-scripts/ProxmoxVED'
    runs-on: ubuntu-latest
    steps:
      - name: Checkout repository
        uses: actions/checkout@v4

      - name: Extract Script Names from Changed Files
        id: extract_scripts
        env:
          GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
        run: |
          CHANGED_FILES=$(gh pr diff ${{ github.event.pull_request.number }} --repo ${{ github.repository }} --name-only)

          SCRIPT_NAMES=()

          while IFS= read -r FILE; do
            if [[ $FILE =~ ^ct/(.+)\.sh$ ]]; then
              SCRIPT_NAME="${BASH_REMATCH[1]}"
              if [[ ! " ${SCRIPT_NAMES[@]} " =~ " ${SCRIPT_NAME} " ]]; then
                SCRIPT_NAMES+=("$SCRIPT_NAME")
              fi
            elif [[ $FILE =~ ^install/(.+)-install\.sh$ ]]; then
              SCRIPT_NAME="${BASH_REMATCH[1]}"
              if [[ ! " ${SCRIPT_NAMES[@]} " =~ " ${SCRIPT_NAME} " ]]; then
                SCRIPT_NAMES+=("$SCRIPT_NAME")
              fi
            fi
          done <<< "$CHANGED_FILES"

          if [ ${#SCRIPT_NAMES[@]} -eq 0 ]; then
            echo "No script files found in PR"
            echo "script_names=[]" >> $GITHUB_OUTPUT
            exit 0
          fi

          JSON_NAMES=$(printf '%s\n' "${SCRIPT_NAMES[@]}" | jq -R . | jq -s -c .)
          echo "script_names=$JSON_NAMES" >> $GITHUB_OUTPUT
          echo "Found script names: ${SCRIPT_NAMES[*]}"

      - name: Process Each Script
        if: steps.extract_scripts.outputs.script_names != '[]'
        uses: actions/github-script@v7
        env:
          PR_AUTHOR: ${{ github.event.pull_request.user.login }}
          SCRIPT_NAMES: ${{ steps.extract_scripts.outputs.script_names }}
        with:
          script: |
            const scriptNames = JSON.parse(process.env.SCRIPT_NAMES);
            const prAuthor = process.env.PR_AUTHOR;
            const message = `@${prAuthor} This PR got merged now and is in the testing phase, it will be migrated to ProxmoxVE when testing is completed`;
            const labelName = 'Ready For Testing';

            for (const scriptName of scriptNames) {
              console.log(`Processing script: ${scriptName}`);

              const { data: issues } = await github.rest.issues.listForRepo({
                owner: context.repo.owner,
                repo: context.repo.repo,
                state: 'open',
                per_page: 100
              });

              const scriptNameLower = scriptName.toLowerCase();
              let existingIssue = issues.find(issue =>
                !issue.pull_request && issue.title.toLowerCase() === scriptNameLower
              );

              if (!existingIssue) {
                const { data: searchResults } = await github.rest.search.issuesAndPullRequests({
                  q: `repo:${context.repo.owner}/${context.repo.repo} is:issue is:open ${scriptName}`,
                  per_page: 100
                });

                existingIssue = searchResults.items.find(issue =>
                  issue.title.toLowerCase() === scriptNameLower
                );
              }

              if (existingIssue) {
                console.log(`Found existing issue #${existingIssue.number}: ${existingIssue.title}`);

                await github.rest.issues.createComment({
                  owner: context.repo.owner,
                  repo: context.repo.repo,
                  issue_number: existingIssue.number,
                  body: message
                });

                const { data: labels } = await github.rest.issues.listLabelsOnIssue({
                  owner: context.repo.owner,
                  repo: context.repo.repo,
                  issue_number: existingIssue.number
                });

                const hasLabel = labels.some(label => label.name === labelName);

                if (!hasLabel) {
                  await github.rest.issues.addLabels({
                    owner: context.repo.owner,
                    repo: context.repo.repo,
                    issue_number: existingIssue.number,
                    labels: [labelName]
                  });
                  console.log(`Added "${labelName}" label to issue #${existingIssue.number}`);
                } else {
                  console.log(`Issue #${existingIssue.number} already has "${labelName}" label`);
                }
              } else {
                console.log(`No existing issue found for "${scriptName}", creating new issue`);

                const scriptType = 'CT (LXC Container)';

                const formattedName = scriptName
                  .split(/[-_]/)
                  .map(word => word.charAt(0).toUpperCase() + word.slice(1).toLowerCase())
                  .join(' ');

                const issueBody = '# 🛠️ **New Script**\n' +
                  'Created by Github Action Bot\n\n' +
                  '### Name of the Script\n\n' +
                  formattedName + '\n\n' +
                  '### Script Type\n\n' +
                  scriptType + '\n\n' +
                  '### 📋 Script Details\n\n' +
                  'This script has been merged and is ready for testing. ';

                const { data: newIssue } = await github.rest.issues.create({
                  owner: context.repo.owner,
                  repo: context.repo.repo,
                  title: scriptName,
                  body: issueBody,
                  labels: [labelName]
                });

                console.log(`Created new issue #${newIssue.number}: ${newIssue.title}`);

                await github.rest.issues.createComment({
                  owner: context.repo.owner,
                  repo: context.repo.repo,
                  issue_number: newIssue.number,
                  body: message
                });
              }
            }

