#!/bin/bash
# Correção DEFINITIVA do erro 503

set -e

echo "🚨 =========================================="
echo "   CORREÇÃO DEFINITIVA - ERRO 503"
echo "=========================================="
echo ""

cd /var/www/gestorstream/backend

# 1. REMOVER ARQUIVO DE MANUTENÇÃO
echo "🔓 [1/8] Removendo arquivo de manutenção..."
rm -f storage/framework/maintenance.php
echo "✅ Removido"
echo ""

# 2. VERIFICAR E CORRIGIR bootstrap/app.php
echo "🔧 [2/8] Verificando bootstrap/app.php..."
if grep -q "preventRequestsDuringMaintenance" bootstrap/app.php; then
    echo "⚠️  Ainda há preventRequestsDuringMaintenance, removendo..."
    # Remover a linha completa do preventRequestsDuringMaintenance
    sed -i '/preventRequestsDuringMaintenance/d' bootstrap/app.php
    echo "✅ Removido"
else
    echo "✅ Já está limpo"
fi
echo ""

# 3. VERIFICAR public/index.php
echo "🔧 [3/8] Verificando public/index.php..."
if grep -q "maintenance" public/index.php; then
    echo "⚠️  Ainda há referências a manutenção, limpando..."
    # Manter apenas o código essencial
    cat > public/index.php.tmp << 'EOF'
<?php

use Illuminate\Foundation\Application;
use Illuminate\Http\Request;

define('LARAVEL_START', microtime(true));

require __DIR__.'/../vendor/autoload.php';

$app = require_once __DIR__.'/../bootstrap/app.php';

$request = Request::capture();

try {
    $response = $app->handleRequest($request);
    $response->send();
    exit(0);
} catch (\Throwable $e) {
    if (!headers_sent()) {
        http_response_code(500);
        header('Content-Type: application/json');
    }
    echo json_encode([
        'error' => 'Internal Server Error',
        'message' => 'An error occurred while processing your request.',
    ]);
    exit(1);
}
EOF
    mv public/index.php.tmp public/index.php
    echo "✅ Limpo"
else
    echo "✅ Já está limpo"
fi
echo ""

# 4. LIMPAR TODOS OS CACHES
echo "🧹 [4/8] Limpando caches..."
php artisan config:clear 2>/dev/null || true
php artisan cache:clear 2>/dev/null || true
php artisan route:clear 2>/dev/null || true
php artisan view:clear 2>/dev/null || true
rm -rf bootstrap/cache/*.php 2>/dev/null || true
echo "✅ Limpos"
echo ""

# 5. REGENERAR AUTOLOADER
echo "🔧 [5/8] Regenerando autoloader..."
COMPOSER_ALLOW_SUPERUSER=1 composer dump-autoload --optimize --no-dev --quiet 2>&1 || true
echo "✅ Regenerado"
echo ""

# 6. CORRIGIR PERMISSÕES
echo "🔐 [6/8] Corrigindo permissões..."
chown -R www-data:www-data storage bootstrap/cache 2>/dev/null || true
chmod -R 775 storage 2>/dev/null || true
chmod -R 775 bootstrap/cache 2>/dev/null || true
echo "✅ Corrigidas"
echo ""

# 7. VERIFICAR SINTAXE PHP
echo "🔍 [7/8] Verificando sintaxe PHP..."
php -l bootstrap/app.php
php -l public/index.php
echo "✅ Sintaxe OK"
echo ""

# 8. REINICIAR SERVIÇOS
echo "🔄 [8/8] Reiniciando serviços..."
PHP_VERSION=$(php -r "echo PHP_MAJOR_VERSION.'.'.PHP_MINOR_VERSION;" 2>/dev/null || echo "8.2")
systemctl restart php${PHP_VERSION}-fpm 2>/dev/null || true
sleep 2
nginx -t && systemctl reload nginx 2>/dev/null || true
echo "✅ Serviços reiniciados"
echo ""

# 9. TESTE FINAL
echo "🧪 Testando..."
sleep 2
HTTP_CODE=$(curl -s -o /dev/null -w "%{http_code}" https://gestor.jf.eng.br/api/v1/setup/check || echo "000")

if [ "$HTTP_CODE" = "200" ]; then
    echo "✅ SUCESSO! Sistema está respondendo com HTTP 200"
elif [ "$HTTP_CODE" = "503" ]; then
    echo "❌ AINDA RETORNA 503"
    echo ""
    echo "📋 Verificando logs..."
    echo "   Últimas linhas do log do Laravel:"
    tail -20 storage/logs/laravel.log 2>/dev/null || echo "   Log não encontrado"
    echo ""
    echo "   Execute manualmente:"
    echo "   php test-503-direct.php"
else
    echo "⚠️  Retornou HTTP $HTTP_CODE (esperado 200)"
fi

echo ""
echo "✅ =========================================="
echo "   CORREÇÃO CONCLUÍDA!"
echo "=========================================="

