#!/bin/bash

echo "=========================================="
echo "TESTE DE BUILD DO FRONTEND"
echo "=========================================="
echo ""

cd /var/www/gestorstream/frontend

echo "1. Verificando imports corrigidos..."
if grep -q "from './ui/Dialog'" src/components/RenewalPaymentModal.tsx; then
    echo "✅ Import do Dialog corrigido"
else
    echo "❌ Import do Dialog ainda incorreto!"
    exit 1
fi

if grep -q "from './ui/Button'" src/components/RenewalPaymentModal.tsx; then
    echo "✅ Import do Button corrigido"
else
    echo "❌ Import do Button ainda incorreto!"
    exit 1
fi
echo ""

echo "2. Compilando frontend..."
sudo -u www-data npm run build

if [ $? -eq 0 ]; then
    echo ""
    echo "✅ BUILD CONCLUÍDO COM SUCESSO!"
    echo ""
    echo "3. Verificando arquivos gerados..."
    if [ -f "dist/index.html" ]; then
        echo "✅ index.html gerado"
        echo "   Tamanho: $(stat -c%s dist/index.html 2>/dev/null || stat -f%z dist/index.html 2>/dev/null) bytes"
    else
        echo "❌ index.html NÃO foi gerado!"
        exit 1
    fi
    
    FILE_COUNT=$(find dist -type f | wc -l)
    echo "✅ Total de arquivos gerados: $FILE_COUNT"
    echo ""
    
    echo "4. Corrigindo permissões..."
    sudo chown -R www-data:www-data dist
    sudo chmod -R 755 dist
    echo "✅ Permissões corrigidas"
    echo ""
    
    echo "5. Recarregando Nginx..."
    sudo nginx -s reload
    echo "✅ Nginx recarregado"
    echo ""
    
    echo "╔══════════════════════════════════════════╗"
    echo "║   ✅  FRONTEND COMPILADO COM SUCESSO!    ║"
    echo "╚══════════════════════════════════════════╝"
    echo ""
    echo "🌐 Teste agora: https://gestor.jf.eng.br/"
    echo ""
else
    echo ""
    echo "❌ ERRO NO BUILD!"
    echo "Verifique os erros acima e corrija."
    exit 1
fi
