name: NPM Audit Fix

on:
  schedule:
    - cron: "0 7 * * 1" # Weekly on Monday at 7 AM UTC
  workflow_dispatch:

jobs:
  npm-audit:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v5
      
      - name: Setup Node.js
        uses: actions/setup-node@v5
        with:
          node-version: "20"
          
      - name: NPM install and audit fix
        working-directory: src/Misc/expressionFunc/hashFiles
        run: |
          npm install
          
          # Check what vulnerabilities exist
          echo "=== Checking current vulnerabilities ==="
          npm audit || true
          
          # Apply audit fix --force to get security updates
          echo "=== Applying npm audit fix --force ==="
          npm audit fix --force
          
          # Test if build still works and set status
          echo "=== Testing build compatibility ==="
          if npm run all; then
            echo "✅ Build successful after audit fix"
            echo "AUDIT_FIX_STATUS=success" >> $GITHUB_ENV
          else
            echo "❌ Build failed after audit fix - will create PR with fix instructions"
            echo "AUDIT_FIX_STATUS=build_failed" >> $GITHUB_ENV
          fi
          
      - name: Create PR if changes exist
        env:
          GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
        run: |
          # Check if there are any changes
          if [ -n "$(git status --porcelain)" ]; then
            # Configure git
            git config --global user.name "github-actions[bot]"
            git config --global user.email "41898282+github-actions[bot]@users.noreply.github.com"
            
            # Create branch and commit changes
            branch_name="chore/npm-audit-fix-$(date +%Y%m%d)"
            git checkout -b "$branch_name"
            git add .
            git commit -m "chore: npm audit fix for hashFiles dependencies" --no-verify
            git push origin "$branch_name"
            
            # Create PR body based on what actually happened
            if [ "$AUDIT_FIX_STATUS" = "success" ]; then
              cat > pr_body.txt << 'EOF'
          Automated npm audit fix for security vulnerabilities in hashFiles dependencies.
          
          **✅ Full Fix Applied Successfully**
          This update addresses npm security advisories and ensures dependencies are secure and up-to-date.
          
          **Changes made:**
          - Applied `npm audit fix --force` to resolve security vulnerabilities
          - Updated package-lock.json with security patches
          - Verified build compatibility with `npm run all`
          
          **Next steps:**
          - Review the dependency changes  
          - Verify the hashFiles functionality still works as expected
          - Merge when ready
          
          ---
          
          Autogenerated by [NPM Audit Fix Workflow](https://github.com/actions/runner/blob/main/.github/workflows/npm-audit.yml)
          EOF
            elif [ "$AUDIT_FIX_STATUS" = "build_failed" ]; then
              cat > pr_body.txt << 'EOF'
          Automated npm audit fix for security vulnerabilities in hashFiles dependencies.
          
          **⚠️ Security Fixes Applied - Build Issues Need Manual Resolution**
          This update applies important security patches but causes build failures that require manual fixes.
          
          **Changes made:**
          - Applied `npm audit fix --force` to resolve security vulnerabilities
          - Updated package-lock.json with security patches
          
          **⚠️ Build Issues Detected:**
          The build fails after applying security fixes, likely due to TypeScript compatibility issues with updated `@types/node`.
          
          **Required Manual Fixes:**
          1. Review TypeScript compilation errors in the build output
          2. Update TypeScript configuration if needed
          3. Consider pinning `@types/node` to a compatible version
          4. Run `npm run all` locally to verify fixes
          
          **Next steps:**
          - **DO NOT merge until build issues are resolved**
          - Apply manual fixes for TypeScript compatibility
          - Test the hashFiles functionality still works as expected
          - Merge when build passes
          
          ---
          
          Autogenerated by [NPM Audit Fix Workflow](https://github.com/actions/runner/blob/main/.github/workflows/npm-audit.yml)
          EOF
            else
              # Fallback case
              cat > pr_body.txt << 'EOF'
          Automated npm audit attempted for security vulnerabilities in hashFiles dependencies.
          
          **ℹ️ No Changes Applied**
          No security vulnerabilities were found or no changes were needed.
          
          ---
          
          Autogenerated by [NPM Audit Fix Workflow](https://github.com/actions/runner/blob/main/.github/workflows/npm-audit.yml)
          EOF
            fi
            
            # Create PR
            gh pr create -B main -H "$branch_name" \
              --title "chore: npm audit fix for hashFiles dependencies" \
              --label "dependencies" \
              --label "dependencies-weekly-check" \
              --label "dependencies-not-dependabot" \
              --label "npm" \
              --label "typescript" \
              --label "security" \
              --body-file pr_body.txt
          else
            echo "✅ No changes to commit - npm audit fix did not modify any files"
          fi
