#!/bin/bash
#
# Restart IDS Frontend (Node.js/Express/Vite)
# Utility per restart manuale del server frontend
#

set -e

echo "🔄 Restart Frontend Node.js..."

# Kill AGGRESSIVO di tutti i processi Node/Vite
echo "⏸️  Stopping all Node/Vite processes..."
pkill -9 -f "node.*tsx" 2>/dev/null || true
pkill -9 -f "vite" 2>/dev/null || true
pkill -9 -f "npm run dev" 2>/dev/null || true
sleep 2

# Kill processo sulla porta 5000 (se esiste)
echo "🔍 Liberando porta 5000..."
lsof -ti:5000 | xargs kill -9 2>/dev/null || true
sleep 1

# Verifica porta LIBERA
if lsof -Pi :5000 -sTCP:LISTEN -t >/dev/null 2>&1; then
    echo "❌ ERRORE: Porta 5000 ancora occupata!"
    echo "Processi sulla porta:"
    lsof -i:5000
    exit 1
fi

echo "✅ Porta 5000 libera"

# Restart usando check_frontend.sh
echo "🚀 Starting frontend..."
/opt/ids/deployment/check_frontend.sh

# Attendi avvio completo
sleep 5

# Verifica avvio
if pgrep -f "vite" > /dev/null; then
    PID=$(pgrep -f "vite")
    echo "✅ Frontend avviato con PID: $PID"
    echo "📡 Server disponibile su: http://localhost:5000"
    
    # Test rapido
    sleep 2
    HTTP_CODE=$(curl -s -o /dev/null -w "%{http_code}" http://localhost:5000/ 2>/dev/null || echo "000")
    if [ "$HTTP_CODE" = "200" ]; then
        echo "✅ HTTP test OK (200)"
    else
        echo "⚠️  HTTP test: $HTTP_CODE"
    fi
else
    echo "❌ Errore: Frontend non avviato!"
    echo "📋 Controlla log: tail -f /var/log/ids/frontend.log"
    exit 1
fi
