#!/bin/bash
#############################################
# Corrigir Nginx e Frontend - Erro 521
#############################################

set -e

INSTALL_DIR="/var/www/gestorstream"
BACKEND_DIR="$INSTALL_DIR/backend"
FRONTEND_DIR="$INSTALL_DIR/frontend"
DOMAIN="derenbox.one"

echo "🔧 Corrigindo Nginx e Frontend..."
echo ""

# 1. Verificar se frontend foi compilado
echo "1. Verificando frontend..."
if [ ! -f "$FRONTEND_DIR/dist/index.html" ]; then
    echo "⚠️  Frontend não compilado. Compilando agora..."
    cd "$FRONTEND_DIR"
    
    # Instalar dependências se necessário
    if [ ! -d "node_modules" ]; then
        echo "  Instalando dependências NPM..."
        npm install --silent
    fi
    
    # Compilar
    echo "  Compilando frontend (isso pode levar alguns minutos)..."
    export NODE_OPTIONS="--max-old-space-size=4096"
    npm run build
    
    if [ ! -f "dist/index.html" ]; then
        echo "❌ ERRO: Frontend não compilou corretamente!"
        exit 1
    fi
    
    echo "✅ Frontend compilado"
else
    echo "✅ Frontend já compilado"
fi

# 2. Corrigir permissões do frontend
echo ""
echo "2. Corrigindo permissões..."
chown -R www-data:www-data "$FRONTEND_DIR/dist"
chmod -R 755 "$FRONTEND_DIR/dist"
echo "✅ Permissões corrigidas"

# 3. Verificar/Criar configuração do Nginx
echo ""
echo "3. Verificando configuração do Nginx..."

if [ ! -f "/etc/nginx/sites-available/gestorstream" ]; then
    echo "⚠️  Configuração do Nginx não encontrada. Criando..."
    
    cat > /etc/nginx/sites-available/gestorstream << EOF
server {
    listen 80;
    listen [::]:80;
    server_name ${DOMAIN};

    root ${FRONTEND_DIR}/dist;
    index index.html;

    # Logs
    access_log /var/log/nginx/gestorstream-access.log;
    error_log /var/log/nginx/gestorstream-error.log;

    # Frontend - SPA
    location / {
        try_files \$uri \$uri/ /index.html;
        add_header Cache-Control "no-cache, no-store, must-revalidate";
    }

    # Backend API
    location /api {
        proxy_pass http://127.0.0.1:8000;
        proxy_http_version 1.1;
        proxy_set_header Upgrade \$http_upgrade;
        proxy_set_header Connection 'upgrade';
        proxy_set_header Host \$host;
        proxy_cache_bypass \$http_upgrade;
        proxy_set_header X-Real-IP \$remote_addr;
        proxy_set_header X-Forwarded-For \$proxy_add_x_forwarded_for;
        proxy_set_header X-Forwarded-Proto \$scheme;
    }

    # Storage (uploads)
    location /storage {
        alias ${BACKEND_DIR}/storage/app/public;
        try_files \$uri \$uri/ =404;
        expires 30d;
        add_header Cache-Control "public, immutable";
    }

    # Arquivos estáticos do frontend
    location ~* \.(js|css|png|jpg|jpeg|gif|ico|svg|woff|woff2|ttf|eot)$ {
        expires 1y;
        add_header Cache-Control "public, immutable";
    }

    client_max_body_size 100M;
}
EOF
    
    echo "✅ Configuração criada"
else
    echo "✅ Configuração já existe"
fi

# 4. Ativar site
echo ""
echo "4. Ativando site no Nginx..."
ln -sf /etc/nginx/sites-available/gestorstream /etc/nginx/sites-enabled/
rm -f /etc/nginx/sites-enabled/default
echo "✅ Site ativado"

# 5. Testar configuração
echo ""
echo "5. Testando configuração do Nginx..."
if nginx -t; then
    echo "✅ Configuração válida"
else
    echo "❌ ERRO na configuração do Nginx!"
    exit 1
fi

# 6. Reiniciar Nginx
echo ""
echo "6. Reiniciando Nginx..."
systemctl restart nginx
echo "✅ Nginx reiniciado"

# 7. Verificar se backend está rodando
echo ""
echo "7. Verificando backend..."
if ! systemctl is-active --quiet gestorstream-backend; then
    echo "⚠️  Backend não está rodando. Iniciando..."
    systemctl start gestorstream-backend
    sleep 2
fi

if systemctl is-active --quiet gestorstream-backend; then
    echo "✅ Backend rodando"
else
    echo "❌ Backend não iniciou. Verifique: journalctl -u gestorstream-backend -n 50"
fi

# 8. Teste final
echo ""
echo "8. Testando acesso local..."
sleep 2

HTTP_CODE=$(curl -s -o /dev/null -w "%{http_code}" http://127.0.0.1 || echo "000")

if [ "$HTTP_CODE" = "200" ]; then
    echo "✅ Nginx respondendo corretamente (HTTP 200)"
elif [ "$HTTP_CODE" = "000" ]; then
    echo "❌ Nginx não está respondendo"
else
    echo "⚠️  Nginx retornou código: $HTTP_CODE"
fi

echo ""
echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
echo "✅ CORREÇÃO CONCLUÍDA!"
echo ""
echo "📊 Status Final:"
echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
systemctl is-active nginx &> /dev/null && echo "  ✅ Nginx: RODANDO" || echo "  ❌ Nginx: PARADO"
systemctl is-active gestorstream-backend &> /dev/null && echo "  ✅ Backend: RODANDO" || echo "  ❌ Backend: PARADO"
[ -f "$FRONTEND_DIR/dist/index.html" ] && echo "  ✅ Frontend: COMPILADO" || echo "  ❌ Frontend: NÃO COMPILADO"
echo ""
echo "🌐 Teste no navegador:"
echo "   http://${DOMAIN}"
echo ""
echo "💡 Se ainda houver erro 521:"
echo "   1. Verifique DNS: ${DOMAIN} deve apontar para este servidor"
echo "   2. No Cloudflare: SSL/TLS → Flexible"
echo "   3. Limpe cache: Caching → Purge Everything"
echo ""
