#!/bin/bash

echo "=========================================="
echo "  CORREÇÃO MANUAL - ERRO 500"
echo "=========================================="
echo ""
echo "Este script irá:"
echo "1. Verificar e atualizar código"
echo "2. Limpar cache"
echo "3. Regenerar autoload"
echo "4. Corrigir permissões"
echo "5. Rebuild frontend"
echo "6. Reiniciar serviços"
echo ""
read -p "Continuar? (s/n) " -n 1 -r
echo ""
if [[ ! $REPLY =~ ^[Ss]$ ]]; then
    echo "Cancelado."
    exit 1
fi

APP_DIR="/var/www/gestorstream"
cd "$APP_DIR" || { echo "Erro: Não foi possível acessar o diretório $APP_DIR"; exit 1; }

echo ""
echo "=========================================="
echo "PASSO 1: Verificar versão atual"
echo "=========================================="
CURRENT_BRANCH=$(git branch --show-current)
CURRENT_COMMIT=$(git log --oneline -1)
echo "Branch: $CURRENT_BRANCH"
echo "Commit: $CURRENT_COMMIT"
echo ""

echo "=========================================="
echo "PASSO 2: Atualizar código"
echo "=========================================="
echo "Fazendo checkout para main..."
git checkout main 2>/dev/null || git checkout -b main origin/main
git pull origin main
echo "✅ Código atualizado"
echo ""

echo "=========================================="
echo "PASSO 3: Atualizar tag v1.0.2"
echo "=========================================="
git tag -f v1.0.2
git push origin -f v1.0.2 2>/dev/null || echo "⚠️  Não foi possível atualizar tag no remoto (pode não ter permissão)"
echo "✅ Tag atualizada"
echo ""

echo "=========================================="
echo "PASSO 4: Backend - Limpar cache"
echo "=========================================="
cd backend
php artisan config:clear
php artisan route:clear
php artisan cache:clear
php artisan view:clear
echo "✅ Cache limpo"
echo ""

echo "=========================================="
echo "PASSO 5: Backend - Regenerar autoload"
echo "=========================================="
composer dump-autoload --no-interaction
echo "✅ Autoload regenerado"
echo ""

echo "=========================================="
echo "PASSO 6: Backend - Verificar sintaxe"
echo "=========================================="
echo "Verificando WhatsAppQueueController..."
if php -l app/Http/Controllers/Api/WhatsAppQueueController.php; then
    echo "✅ Sintaxe OK"
else
    echo "❌ Erro de sintaxe encontrado!"
    exit 1
fi

if [ -f "app/Http/Controllers/Api/WhatsAppDiagnosticController.php" ]; then
    echo "Verificando WhatsAppDiagnosticController..."
    if php -l app/Http/Controllers/Api/WhatsAppDiagnosticController.php; then
        echo "✅ Sintaxe OK"
    else
        echo "❌ Erro de sintaxe encontrado!"
        exit 1
    fi
fi
echo ""

echo "=========================================="
echo "PASSO 7: Frontend - Rebuild"
echo "=========================================="
cd ../frontend
npm install
if npm run build; then
    echo "✅ Frontend compilado com sucesso"
else
    echo "❌ Erro ao compilar frontend!"
    echo "Verifique os erros acima"
    exit 1
fi
echo ""

echo "=========================================="
echo "PASSO 8: Corrigir permissões"
echo "=========================================="
cd ..
chown -R www-data:www-data .
find . -type d -exec chmod 775 {} \;
find . -type f -exec chmod 664 {} \;
chmod +x backend/artisan update.sh diagnostico-erro-500-completo.sh atualizar-tag.sh corrigir-500-manual.sh 2>/dev/null || true
if [ -d "frontend/node_modules/.bin" ]; then
    chmod -R +x frontend/node_modules/.bin/ 2>/dev/null || true
fi
echo "✅ Permissões corrigidas"
echo ""

echo "=========================================="
echo "PASSO 9: Identificar e reiniciar PHP-FPM"
echo "=========================================="
PHP_VERSION=$(php -v | head -1 | grep -oP '\d+\.\d+' | head -1 | cut -d'.' -f1,2)
echo "Versão PHP detectada: $PHP_VERSION"

# Tentar diferentes nomes de serviço
if systemctl list-units --type=service | grep -q "php${PHP_VERSION}-fpm"; then
    echo "Reiniciando php${PHP_VERSION}-fpm..."
    systemctl restart php${PHP_VERSION}-fpm
    echo "✅ PHP-FPM reiniciado"
elif systemctl list-units --type=service | grep -q "php-fpm"; then
    echo "Reiniciando php-fpm..."
    systemctl restart php-fpm
    echo "✅ PHP-FPM reiniciado"
else
    echo "⚠️  Serviço PHP-FPM não encontrado automaticamente"
    echo "Reinicie manualmente: systemctl restart php8.2-fpm (ou sua versão)"
fi
echo ""

echo "=========================================="
echo "PASSO 10: Reiniciar outros serviços"
echo "=========================================="
systemctl restart nginx
echo "✅ Nginx reiniciado"

if systemctl list-units --type=service | grep -q "gestorstream-backend"; then
    systemctl restart gestorstream-backend
    echo "✅ gestorstream-backend reiniciado"
fi

if systemctl list-units --type=service | grep -q "gestorstream-worker"; then
    systemctl restart gestorstream-worker
    echo "✅ gestorstream-worker reiniciado"
fi
echo ""

echo "=========================================="
echo "PASSO 11: Verificar status"
echo "=========================================="
echo "Últimas 5 linhas do log:"
tail -5 backend/storage/logs/laravel.log
echo ""

echo "=========================================="
echo "✅ Correção aplicada!"
echo "=========================================="
echo ""
echo "📋 Próximos passos:"
echo "1. Teste acessar o sistema no navegador"
echo "2. Se ainda houver erro, execute: ./diagnostico-erro-500-completo.sh"
echo "3. Verifique os logs: tail -f backend/storage/logs/laravel.log"
echo ""

