name: Update n8n Dependencies

on:
  # Run every Monday at 9 AM UTC
  schedule:
    - cron: '0 9 * * 1'
  
  # Allow manual trigger
  workflow_dispatch:
    inputs:
      create_pr:
        description: 'Create a PR for updates'
        required: true
        type: boolean
        default: true
      auto_merge:
        description: 'Auto-merge PR if tests pass'
        required: true
        type: boolean
        default: false

jobs:
  check-and-update:
    runs-on: ubuntu-latest
    
    permissions:
      contents: write
      pull-requests: write
    
    steps:
      - name: Checkout repository
        uses: actions/checkout@v4
        with:
          token: ${{ secrets.GITHUB_TOKEN }}
          lfs: true
      
      - name: Setup Node.js
        uses: actions/setup-node@v4
        with:
          node-version: '20'
          cache: 'npm'
      
      - name: Check for updates (dry run)
        id: check
        run: |
          # Ensure we're in the right directory
          cd ${{ github.workspace }}
          
          # First do a dry run to check if updates are needed
          node scripts/update-n8n-deps.js --dry-run > update-check.log 2>&1 || {
            echo "❌ Error running update check:"
            cat update-check.log
            exit 1
          }
          
          # Check if updates are available
          if grep -q "update available" update-check.log; then
            echo "updates_available=true" >> $GITHUB_OUTPUT
            echo "📦 Updates available!"
          else
            echo "updates_available=false" >> $GITHUB_OUTPUT
            echo "✅ All dependencies are up to date"
          fi
          
          # Show the check results
          cat update-check.log
      
      - name: Apply updates
        if: steps.check.outputs.updates_available == 'true'
        id: update
        run: |
          # Ensure we're in the right directory
          cd ${{ github.workspace }}
          
          # Run the actual update
          node scripts/update-n8n-deps.js || {
            echo "❌ Error running update:"
            exit 1
          }
          
          # Check if files changed
          if git diff --quiet; then
            echo "files_changed=false" >> $GITHUB_OUTPUT
          else
            echo "files_changed=true" >> $GITHUB_OUTPUT
          fi
      
      - name: Create update branch
        if: steps.update.outputs.files_changed == 'true' && (github.event_name == 'schedule' || inputs.create_pr)
        id: branch
        run: |
          BRANCH_NAME="update-n8n-deps-$(date +%Y%m%d)"
          echo "branch_name=$BRANCH_NAME" >> $GITHUB_OUTPUT
          
          git config user.name "github-actions[bot]"
          git config user.email "github-actions[bot]@users.noreply.github.com"
          
          git checkout -b $BRANCH_NAME
          git add package.json package-lock.json
          
          # Get update summary (file is written by the update script)
          UPDATE_SUMMARY=$(cat update-summary.txt 2>/dev/null || echo "Updated n8n dependencies")
          
          # Create commit message using heredoc
          COMMIT_MSG=$(cat <<'COMMIT_EOF'
          chore: update n8n dependencies
          
          ${UPDATE_SUMMARY}
          
          🤖 Automated dependency update
          COMMIT_EOF
          )
          # Replace placeholder with actual summary
          COMMIT_MSG="${COMMIT_MSG//\${UPDATE_SUMMARY}/$UPDATE_SUMMARY}"
          
          git commit -m "$COMMIT_MSG"
          git push origin $BRANCH_NAME
          
          # Save update summary as output for PR
          {
            echo 'UPDATE_SUMMARY<<EOF'
            if [ -f update-summary.txt ]; then
              cat update-summary.txt
            else
              echo "See commit for details"
            fi
            echo 'EOF'
          } >> $GITHUB_OUTPUT
      
      - name: Create Pull Request
        if: steps.branch.outputs.branch_name != ''
        uses: peter-evans/create-pull-request@v5
        with:
          token: ${{ secrets.GITHUB_TOKEN }}
          branch: ${{ steps.branch.outputs.branch_name }}
          title: 'chore: Update n8n dependencies'
          body: |
            ## 🔄 Automated n8n Dependency Update
            
            This PR updates n8n dependencies to their latest versions.
            
            ### 📦 Updates
            ```
            ${{ steps.update.outputs.UPDATE_SUMMARY }}
            ```
            
            ### ✅ Validation
            - [x] Dependencies updated
            - [x] Lock file updated
            - [x] Database rebuilt successfully
            - [x] All tests passed
            
            ### 🔍 Review Checklist
            - [ ] Review the [n8n release notes](https://docs.n8n.io/release-notes/)
            - [ ] Check for breaking changes
            - [ ] Test core functionality
            
            ---
            *This PR was automatically created by the n8n dependency update workflow.*
          labels: |
            dependencies
            automated
          assignees: ${{ github.repository_owner }}
          
      - name: Auto-merge PR (if enabled)
        if: steps.branch.outputs.branch_name != '' && inputs.auto_merge
        env:
          GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
        run: |
          # Wait for PR to be created
          sleep 10
          
          # Find the PR
          PR_NUMBER=$(gh pr list --head ${{ steps.branch.outputs.branch_name }} --json number -q '.[0].number')
          
          if [ -n "$PR_NUMBER" ]; then
            echo "Auto-merging PR #$PR_NUMBER..."
            gh pr merge $PR_NUMBER --merge --auto
          fi

  # Direct commit option (for manual trigger)
  direct-update:
    if: github.event_name == 'workflow_dispatch' && !inputs.create_pr
    runs-on: ubuntu-latest
    
    permissions:
      contents: write
    
    steps:
      - name: Checkout repository
        uses: actions/checkout@v4
        with:
          token: ${{ secrets.GITHUB_TOKEN }}
          lfs: true
      
      - name: Setup Node.js
        uses: actions/setup-node@v4
        with:
          node-version: '20'
          cache: 'npm'
      
      - name: Update dependencies
        run: |
          node scripts/update-n8n-deps.js
          
          # Check if files changed
          if ! git diff --quiet; then
            git config user.name "github-actions[bot]"
            git config user.email "github-actions[bot]@users.noreply.github.com"
            
            git add package.json package-lock.json
            
            # Get update summary
            UPDATE_SUMMARY=$(cat update-summary.txt || echo "Updated n8n dependencies")
            
            # Create commit message using heredoc
            COMMIT_MSG=$(cat <<'COMMIT_EOF'
            chore: update n8n dependencies
            
            ${UPDATE_SUMMARY}
            
            🤖 Automated dependency update
            COMMIT_EOF
            )
            # Replace placeholder with actual summary
            COMMIT_MSG="${COMMIT_MSG//\${UPDATE_SUMMARY}/$UPDATE_SUMMARY}"
            
            git commit -m "$COMMIT_MSG"
            
            git push
          else
            echo "No updates needed"
          fi