name: ⚡ Quick Security Scan
# StackWorkflow v2.2 - Verificação Rápida

on:
  push:
    paths-ignore:
      - 'README.md'
      - 'docs/**'
      - '.gitignore'
  pull_request:
    paths-ignore:
      - 'README.md'
      - 'docs/**'
      - '.gitignore'

env:
  CRITICAL_THRESHOLD: 5

jobs:
  quick-scan:
    name: 🚨 Quick Vulnerability Detection
    runs-on: ubuntu-latest

    steps:
    - name: 📥 Checkout Code
      uses: actions/checkout@v4

    - name: 🔍 Lightning Fast Security Scan
      id: scan
      run: |
        echo "⚡ Executando scan rápido de segurança..."

        # SQL Injection (mais rigoroso)
        SQL_CRITICAL=$(find . -name "*.php" -type f ! -path "./vendor/*" ! -path "./node_modules/*" ! -path "./.git/*" -exec grep -l '\$_GET\|\$_POST' {} \; | xargs grep -l 'echo\|print' 2>/dev/null | wc -l)

        # XSS direto
        XSS_CRITICAL=$(find . \( -name "*.php" -o -name "*.html" \) -type f ! -path "./vendor/*" ! -path "./node_modules/*" ! -path "./.git/*" -exec grep -l 'echo.*\$_' {} \; 2>/dev/null | wc -l)

        # Eval perigoso
        EVAL_CRITICAL=$(find . -name "*.php" -type f ! -path "./vendor/*" ! -path "./node_modules/*" ! -path "./.git/*" -exec grep -l 'eval(' {} \; 2>/dev/null | wc -l)

        # Secrets expostos
        SECRETS_CRITICAL=$(find . -type f ! -path "./vendor/*" ! -path "./node_modules/*" ! -path "./.git/*" ! -name "*.md" -exec grep -l "password.*=.*[\"'][^\"']*[\"']\|api_key.*=.*[\"'][^\"']*[\"']\|secret.*=.*[\"'][^\"']*[\"']" {} \; 2>/dev/null | wc -l)

        TOTAL_CRITICAL=$((SQL_CRITICAL + XSS_CRITICAL + EVAL_CRITICAL + SECRETS_CRITICAL))

        echo "sql_critical=$SQL_CRITICAL" >> $GITHUB_OUTPUT
        echo "xss_critical=$XSS_CRITICAL" >> $GITHUB_OUTPUT
        echo "eval_critical=$EVAL_CRITICAL" >> $GITHUB_OUTPUT
        echo "secrets_critical=$SECRETS_CRITICAL" >> $GITHUB_OUTPUT
        echo "total_critical=$TOTAL_CRITICAL" >> $GITHUB_OUTPUT

        # Logging detalhado
        echo "📊 SCAN RESULTS:"
        echo "- SQL Injection Crítico: $SQL_CRITICAL"
        echo "- XSS Crítico: $XSS_CRITICAL"
        echo "- Eval() Perigoso: $EVAL_CRITICAL"
        echo "- Secrets Expostos: $SECRETS_CRITICAL"
        echo "- TOTAL CRÍTICO: $TOTAL_CRITICAL"

        # Mostrar exemplos se encontrados
        if [ $SQL_CRITICAL -gt 0 ]; then
          echo "🔴 Exemplos SQL Injection:"
          find . -name "*.php" -type f ! -path "./vendor/*" ! -path "./node_modules/*" ! -path "./.git/*" -exec grep -l '\$_GET\|\$_POST' {} \; | xargs grep -n 'echo\|print' 2>/dev/null | head -3
        fi

        if [ $SECRETS_CRITICAL -gt 0 ]; then
          echo "🔴 Possíveis secrets expostos:"
          find . -type f ! -path "./vendor/*" ! -path "./node_modules/*" ! -path "./.git/*" ! -name "*.md" -exec grep -n "password.*=.*[\"'][^\"']*[\"']\|api_key.*=.*[\"'][^\"']*[\"']" {} \; 2>/dev/null | head -3 | sed 's/=.*/=***HIDDEN***/'
        fi

    - name: 🚦 Critical Security Gate
      run: |
        if [ ${{ steps.scan.outputs.total_critical }} -gt ${{ env.CRITICAL_THRESHOLD }} ]; then
          echo "🔴 BLOQUEADO: ${{ steps.scan.outputs.total_critical }} vulnerabilidades críticas detectadas!"
          echo "🔴 Threshold: ${{ env.CRITICAL_THRESHOLD }} vulnerabilidades máximas"
          echo ""
          echo "📋 BREAKDOWN:"
          echo "- SQL Injection: ${{ steps.scan.outputs.sql_critical }}"
          echo "- XSS: ${{ steps.scan.outputs.xss_critical }}"
          echo "- Eval(): ${{ steps.scan.outputs.eval_critical }}"
          echo "- Secrets: ${{ steps.scan.outputs.secrets_critical }}"
          echo ""
          echo "🔧 AÇÃO REQUERIDA: Corrigir vulnerabilidades antes de mergear."
          exit 1
        else
          echo "✅ APROVADO: ${{ steps.scan.outputs.total_critical }} vulnerabilidades (≤ ${{ env.CRITICAL_THRESHOLD }})"
        fi

    - name: 📊 Generate Quick Report
      if: always()
      run: |
        mkdir -p reports

        cat > reports/quick-scan-$(date +%Y%m%d_%H%M%S).md << EOF
        # ⚡ Quick Security Scan Report

        **Data**: $(date '+%Y-%m-%d %H:%M:%S')
        **Commit**: ${{ github.sha }}
        **Branch**: ${{ github.ref_name }}
        **Status**: ${{ job.status }}

        ## 🚨 Vulnerabilidades Críticas

        | Tipo | Quantidade | Criticidade |
        |------|------------|-------------|
        | SQL Injection | ${{ steps.scan.outputs.sql_critical }} | 🔴 CRÍTICA |
        | XSS | ${{ steps.scan.outputs.xss_critical }} | 🔴 CRÍTICA |
        | Eval() | ${{ steps.scan.outputs.eval_critical }} | 🔴 CRÍTICA |
        | Secrets Expostos | ${{ steps.scan.outputs.secrets_critical }} | 🔴 CRÍTICA |
        | **TOTAL** | **${{ steps.scan.outputs.total_critical }}** | **Threshold: ${{ env.CRITICAL_THRESHOLD }}** |

        ## 🎯 Resultado

        EOF

        if [ ${{ steps.scan.outputs.total_critical }} -gt ${{ env.CRITICAL_THRESHOLD }} ]; then
          echo "**🔴 REPROVADO**: Vulnerabilidades críticas excedem o limite permitido." >> reports/quick-scan-$(date +%Y%m%d_%H%M%S).md
          echo "" >> reports/quick-scan-$(date +%Y%m%d_%H%M%S).md
          echo "🔧 **Ação necessária**: Corrigir vulnerabilidades antes de prosseguir." >> reports/quick-scan-$(date +%Y%m%d_%H%M%S).md
        else
          echo "**✅ APROVADO**: Projeto dentro dos limites de segurança aceitáveis." >> reports/quick-scan-$(date +%Y%m%d_%H%M%S).md
          echo "" >> reports/quick-scan-$(date +%Y%m%d_%H%M%S).md
          echo "💡 **Recomendação**: Executar auditoria completa com \`/avaliar\` para análise detalhada." >> reports/quick-scan-$(date +%Y%m%d_%H%M%S).md
        fi

        echo "" >> reports/quick-scan-$(date +%Y%m%d_%H%M%S).md
        echo "---" >> reports/quick-scan-$(date +%Y%m%d_%H%M%S).md
        echo "**Powered by**: StackWorkflow v2.2 Quick Scan" >> reports/quick-scan-$(date +%Y%m%d_%H%M%S).md

    - name: 📤 Upload Quick Report
      if: always()
      uses: actions/upload-artifact@v4
      with:
        name: quick-scan-report
        path: reports/*.md
        retention-days: 7

    - name: 💬 Quick Status Comment
      if: github.event_name == 'pull_request' && always()
      uses: actions/github-script@v7
      with:
        script: |
          const total = '${{ steps.scan.outputs.total_critical }}';
          const threshold = '${{ env.CRITICAL_THRESHOLD }}';
          const status = total > threshold ? 'BLOCKED' : 'APPROVED';
          const emoji = total > threshold ? '🔴' : '✅';

          const body = `${emoji} **Quick Security Scan: ${status}**

          | Vulnerabilidade | Encontradas |
          |-----------------|-------------|
          | SQL Injection | ${{ steps.scan.outputs.sql_critical }} |
          | XSS | ${{ steps.scan.outputs.xss_critical }} |
          | Eval() | ${{ steps.scan.outputs.eval_critical }} |
          | Secrets | ${{ steps.scan.outputs.secrets_critical }} |
          | **TOTAL** | **${total}** / ${threshold} |

          ${total > threshold ?
          '🔧 **Action Required**: Fix critical vulnerabilities before merging.' :
          '💡 **Next Step**: Run full audit with `/avaliar` for detailed analysis.'
          }
          `;

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