#!/bin/bash

# Script de verificación de seguridad para AI Learning Platform
# Ejecutar: ./security-audit.sh

set -e

echo "🔒 AI Learning Platform - Security Audit Script"
echo "=============================================="

# Colors for output
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
NC='\033[0m' # No Color

# Check if running from project root
if [ ! -f "docker-compose.yml" ]; then
    echo -e "${RED}❌ Error: docker-compose.yml not found.${NC}"
    echo -e "${YELLOW}Please run this script from the project root directory.${NC}"
    exit 1
fi

echo ""
echo -e "${BLUE}📋 Verificando vulnerabilidades de seguridad en todos los proyectos...${NC}"
echo ""

# Function to audit a directory
audit_directory() {
    local dir=$1
    local name=$2
    
    echo -e "${BLUE}🔍 Verificando $name...${NC}"
    
    if [ ! -d "$dir" ]; then
        echo -e "${YELLOW}   ⚠️  Directorio $dir no encontrado, saltando...${NC}"
        return 0
    fi
    
    if [ ! -f "$dir/package.json" ]; then
        echo -e "${YELLOW}   ⚠️  package.json no encontrado en $dir, saltando...${NC}"
        return 0
    fi
    
    cd "$dir"
    
    # Run audit
    if npm audit --audit-level=moderate > /dev/null 2>&1; then
        echo -e "${GREEN}   ✅ No hay vulnerabilidades en $name${NC}"
        cd ..
        return 0
    else
        echo -e "${YELLOW}   ⚠️  Vulnerabilidades encontradas en $name${NC}"
        
        # Show detailed audit
        echo -e "${BLUE}   📊 Detalles de vulnerabilidades:${NC}"
        npm audit --audit-level=moderate | head -20
        
        echo ""
        echo -e "${BLUE}   🔧 Aplicando correcciones automáticas...${NC}"
        
        if npm audit fix; then
            echo -e "${GREEN}   ✅ Vulnerabilidades corregidas en $name${NC}"
        else
            echo -e "${YELLOW}   ⚠️  No se pudieron corregir todas las vulnerabilidades en $name${NC}"
            echo -e "${BLUE}   💡 Revisa manualmente: cd $dir && npm audit${NC}"
        fi
        
        cd ..
        return 1
    fi
}

# Track if any vulnerabilities were found
VULNERABILITIES_FOUND=0

# Audit root directory
if ! audit_directory "." "directorio raíz"; then
    VULNERABILITIES_FOUND=1
fi

echo ""

# Audit backend
if ! audit_directory "backend" "backend"; then
    VULNERABILITIES_FOUND=1
fi

echo ""

# Audit frontend
if ! audit_directory "frontend" "frontend"; then
    VULNERABILITIES_FOUND=1
fi

echo ""

# Summary
echo -e "${BLUE}📊 RESUMEN DE VERIFICACIÓN DE SEGURIDAD${NC}"
echo "=============================================="

if [ $VULNERABILITIES_FOUND -eq 0 ]; then
    echo -e "${GREEN}✅ ¡Excelente! No se encontraron vulnerabilidades de seguridad.${NC}"
    echo -e "${GREEN}   Tu aplicación está segura y actualizada.${NC}"
else
    echo -e "${YELLOW}⚠️  Se encontraron vulnerabilidades que requieren atención.${NC}"
    echo -e "${YELLOW}   Revisa los detalles arriba y considera actualizaciones manuales.${NC}"
fi

echo ""
echo -e "${BLUE}🔧 COMANDOS ÚTILES:${NC}"
echo -e "  Verificar vulnerabilidades:     npm audit"
echo -e "  Corregir automáticamente:       npm audit fix"
echo -e "  Verificar vulnerabilidades altas: npm audit --audit-level=high"
echo -e "  Actualizar dependencias:        npm update"
echo -e "  Verificar actualizaciones:      npm outdated"

echo ""
echo -e "${BLUE}📋 PRÓXIMOS PASOS RECOMENDADOS:${NC}"
echo -e "  1. Revisa las vulnerabilidades reportadas"
echo -e "  2. Actualiza las dependencias críticas manualmente si es necesario"
echo -e "  3. Ejecuta este script regularmente (semanalmente)"
echo -e "  4. Considera configurar dependabot para actualizaciones automáticas"

echo ""
echo -e "${GREEN}✅ Verificación de seguridad completada${NC}"
