#!/bin/bash

# Script para diagnosticar e corrigir problemas na atualização

echo "========================================="
echo "🔍 DIAGNÓSTICO DE ATUALIZAÇÃO"
echo "========================================="
echo ""

BACKEND_DIR="/var/www/gestorstream/backend"
FRONTEND_DIR="/var/www/gestorstream/frontend"

# 1. Verificar processos travados
echo "1. Verificando processos travados..."
echo "----------------------------------------"
ps aux | grep -E "artisan|migrate|npm|node|vite" | grep -v grep
echo ""

# 2. Verificar status da última atualização
echo "2. Verificando última atualização no banco..."
echo "----------------------------------------"
cd "$BACKEND_DIR" || exit 1
php artisan tinker --execute="
\$update = \App\Models\SystemUpdate::latest()->first();
if (\$update) {
    echo 'ID: ' . \$update->id . PHP_EOL;
    echo 'Versão: ' . \$update->version . PHP_EOL;
    echo 'Status: ' . \$update->status . PHP_EOL;
    echo 'Iniciado em: ' . \$update->created_at . PHP_EOL;
    echo 'Última atualização: ' . \$update->updated_at . PHP_EOL;
    echo PHP_EOL . 'Últimas linhas do log:' . PHP_EOL;
    echo substr(\$update->logs, -500);
} else {
    echo 'Nenhuma atualização encontrada' . PHP_EOL;
}
"
echo ""

# 3. Verificar migrations pendentes
echo "3. Verificando migrations pendentes..."
echo "----------------------------------------"
php artisan migrate:status 2>&1 | tail -20
echo ""

# 4. Verificar se dist/index.html existe
echo "4. Verificando dist/index.html..."
echo "----------------------------------------"
if [ -f "$FRONTEND_DIR/dist/index.html" ]; then
    echo "✅ index.html existe"
    ls -lh "$FRONTEND_DIR/dist/index.html"
    echo "Permissões: $(stat -c '%a' "$FRONTEND_DIR/dist/index.html")"
else
    echo "❌ index.html NÃO existe!"
    echo "Isso causará erro 403"
fi
echo ""

# 5. Verificar arquivo VERSION
echo "5. Verificando arquivo VERSION..."
echo "----------------------------------------"
if [ -f "$BACKEND_DIR/VERSION" ]; then
    echo "Versão atual: $(cat "$BACKEND_DIR/VERSION")"
else
    echo "❌ Arquivo VERSION não encontrado"
fi
echo ""

# 6. Verificar logs recentes
echo "6. Últimas linhas do log do Laravel..."
echo "----------------------------------------"
tail -30 "$BACKEND_DIR/storage/logs/laravel.log" 2>/dev/null || echo "Log não encontrado"
echo ""

# 7. Verificar log do build do frontend
echo "7. Últimas linhas do log do build do frontend..."
echo "----------------------------------------"
if [ -f "$BACKEND_DIR/storage/logs/frontend_build.log" ]; then
    tail -30 "$BACKEND_DIR/storage/logs/frontend_build.log"
else
    echo "Log de build não encontrado"
fi
echo ""

echo "========================================="
echo "✅ Diagnóstico concluído"
echo "========================================="

