# 🔧 CORREÇÃO: Erro 500 no Download de Backup + Erro 403 no Novo Servidor

## 🔴 PROBLEMA 1: Erro 500 ao Baixar Backup

### **Sintoma:**
```
GET /api/v1/admin/database/backup/download?backup_file=backup_mysql_2026-01-14_14-52-28.sql&backup_type=local
Status: 500 (Internal Server Error)
```

### **Causa:**
O método `getBackupPath()` lançava uma exceção quando o arquivo não existia, mas o controller não tratava adequadamente essa exceção antes de verificar se o arquivo existia.

### **Correção Aplicada:**

**Arquivo:** `backend/app/Http/Controllers/Api/DatabaseBackupController.php`

**Mudanças:**
1. ✅ Tratamento adequado da exceção de `getBackupPath()`
2. ✅ Logs detalhados para diagnóstico
3. ✅ Mensagens de erro mais claras
4. ✅ Verificação de permissões com informações detalhadas

**Agora o código:**
- Captura a exceção se o arquivo não existir
- Retorna 404 (não 500) quando arquivo não encontrado
- Retorna 403 com mensagem clara quando arquivo não pode ser lido
- Registra logs detalhados para diagnóstico

---

## 🔴 PROBLEMA 2: Erro 403 no Novo Servidor

### **Sintoma:**
Após importar o sistema para um novo servidor, aparece erro **403 Forbidden** ao acessar a aplicação.

### **Causas Possíveis:**

#### **1. `index.html` não existe em `frontend/dist/`**

**Verificar:**
```bash
ls -lh /var/www/gestorstream/frontend/dist/index.html
```

**Solução:**
```bash
cd /var/www/gestorstream/frontend
npm install
npm run build

# Verificar se foi criado
ls -lh dist/index.html
```

---

#### **2. Permissões Incorretas**

**Verificar:**
```bash
# Verificar ownership
ls -la /var/www/gestorstream/frontend/dist/
ls -la /var/www/gestorstream/backend/storage/
```

**Solução:**
```bash
cd /var/www/gestorstream

# Ajustar ownership
sudo chown -R www-data:www-data backend/
sudo chown -R www-data:www-data frontend/

# Ajustar permissões
sudo chmod -R 755 backend/
sudo chmod -R 755 frontend/

# Permissões específicas para storage
sudo chmod -R 775 backend/storage/
sudo chmod -R 775 backend/bootstrap/cache/
```

---

#### **3. Configuração do Nginx Incorreta**

**Verificar configuração do Nginx:**
```bash
sudo nano /etc/nginx/sites-available/gestorstream
```

**Configuração correta para frontend:**

```nginx
server {
    listen 80;
    server_name gestor.jf.eng.br;
    
    root /var/www/gestorstream/frontend/dist;
    index index.html;

    # Frontend - SPA
    location / {
        try_files $uri $uri/ /index.html;
    }

    # Backend API
    location /api {
        alias /var/www/gestorstream/backend/public;
        try_files $uri $uri/ /index.php?$query_string;
        
        location ~ \.php$ {
            include snippets/fastcgi-php.conf;
            fastcgi_pass unix:/var/run/php/php8.2-fpm.sock;
            fastcgi_param SCRIPT_FILENAME $request_filename;
        }
    }

    # PHP files
    location ~ \.php$ {
        include snippets/fastcgi-php.conf;
        fastcgi_pass unix:/var/run/php/php8.2-fpm.sock;
    }

    # Deny access to hidden files
    location ~ /\. {
        deny all;
    }
}
```

**Aplicar configuração:**
```bash
# Testar configuração
sudo nginx -t

# Recarregar Nginx
sudo systemctl reload nginx
```

---

#### **4. SELinux (se habilitado)**

**Verificar:**
```bash
getenforce
```

**Se estiver em "Enforcing", desabilitar temporariamente:**
```bash
sudo setenforce 0
```

**Ou configurar contextos corretos:**
```bash
sudo chcon -R -t httpd_sys_content_t /var/www/gestorstream/
sudo chcon -R -t httpd_sys_rw_content_t /var/www/gestorstream/backend/storage/
```

---

## 🚀 SCRIPT DE CORREÇÃO COMPLETO PARA NOVO SERVIDOR

Crie e execute este script no novo servidor:

```bash
#!/bin/bash
# fix-403-new-server.sh

set -e

APP_DIR="/var/www/gestorstream"
echo "🔧 Corrigindo erro 403 no novo servidor..."

# 1. Verificar se diretório existe
if [ ! -d "$APP_DIR" ]; then
    echo "❌ Erro: Diretório $APP_DIR não encontrado"
    exit 1
fi

cd "$APP_DIR"

# 2. Rebuild frontend
echo "📦 Reconstruindo frontend..."
cd frontend
npm install
npm run build

# Verificar se index.html foi criado
if [ ! -f "dist/index.html" ]; then
    echo "❌ ERRO: index.html não foi criado após build!"
    echo "Verifique os logs do npm run build"
    exit 1
fi
echo "✅ Frontend reconstruído"

# 3. Ajustar permissões
echo "🔐 Ajustando permissões..."
cd "$APP_DIR"

# Ownership
sudo chown -R www-data:www-data backend/
sudo chown -R www-data:www-data frontend/

# Permissões gerais
sudo chmod -R 755 backend/
sudo chmod -R 755 frontend/

# Permissões específicas
sudo chmod -R 775 backend/storage/
sudo chmod -R 775 backend/bootstrap/cache/
sudo chmod -R 755 frontend/dist/

# 4. Verificar Nginx
echo "🌐 Verificando Nginx..."
if [ -f "/etc/nginx/sites-available/gestorstream" ]; then
    sudo nginx -t
    if [ $? -eq 0 ]; then
        sudo systemctl reload nginx
        echo "✅ Nginx recarregado"
    else
        echo "⚠️  Erro na configuração do Nginx. Verifique manualmente."
    fi
else
    echo "⚠️  Configuração do Nginx não encontrada. Configure manualmente."
fi

# 5. Verificar PHP-FPM
echo "🐘 Verificando PHP-FPM..."
if systemctl is-active --quiet php8.2-fpm; then
    sudo systemctl restart php8.2-fpm
    echo "✅ PHP-FPM reiniciado"
fi

# 6. Verificar index.html
echo "📄 Verificando index.html..."
if [ -f "$APP_DIR/frontend/dist/index.html" ]; then
    echo "✅ index.html existe"
    ls -lh "$APP_DIR/frontend/dist/index.html"
else
    echo "❌ ERRO: index.html NÃO existe!"
    echo "Execute manualmente: cd $APP_DIR/frontend && npm run build"
    exit 1
fi

# 7. Verificar permissões do index.html
if [ -r "$APP_DIR/frontend/dist/index.html" ]; then
    echo "✅ index.html é legível"
else
    echo "⚠️  index.html não é legível. Ajustando permissões..."
    sudo chmod 644 "$APP_DIR/frontend/dist/index.html"
fi

echo ""
echo "✅ CORREÇÃO CONCLUÍDA!"
echo ""
echo "📋 Verificações finais:"
echo "   1. Acesse: https://gestor.jf.eng.br"
echo "   2. Se ainda der 403, verifique os logs:"
echo "      - sudo tail -f /var/log/nginx/error.log"
echo "      - sudo tail -f $APP_DIR/backend/storage/logs/laravel.log"
echo ""
```

**Salvar e executar:**
```bash
# Salvar script
nano fix-403-new-server.sh
# (cole o conteúdo acima)

# Dar permissão de execução
chmod +x fix-403-new-server.sh

# Executar
sudo bash fix-403-new-server.sh
```

---

## 🔍 DIAGNÓSTICO PASSO A PASSO

### **1. Verificar se index.html existe:**
```bash
ls -lh /var/www/gestorstream/frontend/dist/index.html
```

**Se não existir:**
```bash
cd /var/www/gestorstream/frontend
npm install
npm run build
```

---

### **2. Verificar permissões:**
```bash
# Ver ownership
ls -la /var/www/gestorstream/frontend/dist/

# Deve mostrar www-data:www-data
# Se mostrar root:root, corrigir:
sudo chown -R www-data:www-data /var/www/gestorstream/
```

---

### **3. Verificar logs do Nginx:**
```bash
sudo tail -f /var/log/nginx/error.log
```

**Erros comuns:**
- `Permission denied` → Ajustar permissões
- `No such file or directory` → index.html não existe
- `Directory index forbidden` → Configuração do Nginx incorreta

---

### **4. Verificar configuração do Nginx:**
```bash
sudo nginx -t
```

**Se houver erros, corrigir:**
```bash
sudo nano /etc/nginx/sites-available/gestorstream
# (usar configuração acima)
sudo nginx -t
sudo systemctl reload nginx
```

---

### **5. Testar acesso direto ao index.html:**
```bash
curl -I http://localhost/
```

**Deve retornar:**
```
HTTP/1.1 200 OK
```

**Se retornar 403:**
- Verificar permissões do arquivo
- Verificar configuração do Nginx
- Verificar SELinux (se habilitado)

---

## 📊 CHECKLIST DE VERIFICAÇÃO

Após aplicar as correções, verificar:

- [ ] `index.html` existe em `frontend/dist/`
- [ ] Permissões corretas (755 para diretórios, 644 para arquivos)
- [ ] Ownership correto (www-data:www-data)
- [ ] Nginx configurado corretamente
- [ ] Nginx testado (`nginx -t`)
- [ ] Nginx recarregado (`systemctl reload nginx`)
- [ ] PHP-FPM rodando
- [ ] Logs do Nginx sem erros
- [ ] Acesso via browser funciona

---

## 🎯 RESOLUÇÃO RÁPIDA (TL;DR)

**No novo servidor, execute:**

```bash
cd /var/www/gestorstream

# 1. Rebuild frontend
cd frontend
npm install
npm run build

# 2. Ajustar permissões
cd ..
sudo chown -R www-data:www-data .
sudo chmod -R 755 .
sudo chmod -R 775 backend/storage backend/bootstrap/cache

# 3. Recarregar serviços
sudo systemctl reload nginx
sudo systemctl restart php8.2-fpm

# 4. Verificar
ls -lh frontend/dist/index.html
curl -I http://localhost/
```

**Se ainda der erro 403, verificar logs:**
```bash
sudo tail -f /var/log/nginx/error.log
```

---

## ✅ RESULTADO ESPERADO

Após aplicar todas as correções:

1. ✅ **Download de backup:** Retorna 404 se arquivo não existir (não mais 500)
2. ✅ **Novo servidor:** Acesso funciona sem erro 403
3. ✅ **Logs detalhados:** Facilita diagnóstico futuro

---

## 📞 SE AINDA NÃO FUNCIONAR

**Coletar informações:**
```bash
# 1. Verificar index.html
ls -lh /var/www/gestorstream/frontend/dist/index.html

# 2. Verificar permissões
ls -la /var/www/gestorstream/frontend/dist/

# 3. Verificar logs do Nginx
sudo tail -50 /var/log/nginx/error.log

# 4. Verificar configuração do Nginx
sudo nginx -t
cat /etc/nginx/sites-available/gestorstream | grep -A 10 "location /"

# 5. Testar acesso
curl -v http://localhost/ 2>&1 | head -20
```

**Enviar essas informações para diagnóstico adicional.**
