# 🔍 CORREÇÃO: Sistema de Logs do Webhook Gitea

## 📋 PROBLEMA IDENTIFICADO

**Sintoma:** Webhooks do Gitea estavam chegando ao servidor (confirmado pelos logs do Nginx), mas NÃO geravam logs no Laravel, impossibilitando o diagnóstico.

**Logs do Nginx mostravam:**
```
138.118.204.32 - - [12/Jan/2026:14:31:21] "POST /api/webhooks/gitea HTTP/1.1" 200 57
138.118.204.32 - - [12/Jan/2026:14:38:38] "POST /api/webhooks/gitea HTTP/1.1" 200 57
```
✅ Webhooks chegando (200 OK)  
❌ Sem logs no Laravel

---

## 🛠️ CORREÇÕES IMPLEMENTADAS

### 1. **Logs Detalhados no Controller** (`UpdateWebhookController.php`)

Adicionados logs em TODOS os pontos críticos:

#### ✅ Início da Requisição (SEMPRE executa)
```php
Log::info('=== UpdateWebhook: INÍCIO ===', [
    'method' => $request->method(),
    'ip' => $request->ip(),
    'headers' => [...],
]);
```

#### ✅ Carregamento de Configurações
```php
Log::info('UpdateWebhook: Settings loaded', [
    'has_settings' => !empty($settings),
    'auto_update' => $settings->auto_update_enabled ?? false,
    'gitea_url' => $settings->gitea_url ?? null,
    'repository' => $settings->repository ?? null,
]);
```

#### ✅ Validação de Assinatura
```php
Log::info('UpdateWebhook: Validating signature...');
// ... validação ...
Log::info('UpdateWebhook: Signature validated successfully ✓');
```

#### ✅ Processamento de Payload
```php
Log::info('UpdateWebhook: Payload parsed successfully');
Log::info('UpdateWebhook: Processing event', [
    'event' => $event,
    'action' => $data['action'] ?? null,
]);
```

#### ✅ Handlers de Eventos
```php
Log::info('UpdateWebhook: Handling RELEASE event');
Log::info('=== UpdateWebhook: handleReleaseEvent STARTED ===');
// ... processamento ...
Log::info('=== UpdateWebhook: handleReleaseEvent FINISHED ===');
```

#### ✅ Status de Auto-Update
```php
Log::warning("UpdateWebhook: Auto-update is DISABLED", [
    'has_settings' => !empty($settings),
    'auto_update_enabled' => $settings->auto_update_enabled ?? false,
    'recommendation' => 'Enable auto_update_enabled in Gitea settings',
]);
```

---

### 2. **Script de Diagnóstico Atualizado** (`test-gitea-webhook-complete.sh`)

**Problema:** Script estava buscando em `SystemSetting` (tabela antiga)  
**Solução:** Atualizado para buscar em `GiteaSettings` (tabela correta)

**Antes:**
```bash
GITEA_URL=$(php artisan tinker --execute="echo \App\Models\SystemSetting::get('gitea_url');")
```

**Depois:**
```bash
SETTINGS_JSON=$(php artisan tinker --execute="\$s = \App\Models\GiteaSettings::getActive(); echo \$s ? json_encode([...]) : 'null';")
```

**Agora mostra:**
```
✓ Configurações encontradas:
  - Gitea URL: https://git.jf.eng.br
  - Repository: jfeng/GestorStream
  - Webhook Secret: ✓ Configurado
  - Auto-update: ✓ HABILITADO
  - Status: ✓ Ativo
```

---

## 🧪 COMO TESTAR

### Opção 1: Teste Manual com Script

```bash
cd /var/www/gestorstream
chmod +x test-gitea-webhook-complete.sh
sudo bash test-gitea-webhook-complete.sh
```

**O script agora:**
1. ✅ Busca configurações no lugar correto (`GiteaSettings`)
2. ✅ Testa endpoint local
3. ✅ Simula webhook real com payload
4. ✅ Verifica logs do Laravel
5. ✅ Verifica logs do Nginx
6. ✅ Dá instruções para verificar no Gitea

---

### Opção 2: Monitorar Logs em Tempo Real

```bash
# Terminal 1: Limpar e monitorar logs
cd /var/www/gestorstream/backend
echo "" > storage/logs/laravel.log
tail -f storage/logs/laravel.log | grep -i "webhook\|gitea\|release\|update"

# Terminal 2 (ou Gitea UI): Testar webhook
curl -X POST -H "Content-Type: application/json" -H "X-Gitea-Event: release" \
  -d '{"action":"published","release":{"tag_name":"v1.0.2-test"}}' \
  https://gestor.jf.eng.br/api/webhooks/gitea
```

**Agora você DEVE ver logs como:**
```
[timestamp] UpdateWebhook: INÍCIO
[timestamp] UpdateWebhook: POST request received
[timestamp] UpdateWebhook: Settings loaded (auto_update: true)
[timestamp] UpdateWebhook: Validating signature...
[timestamp] UpdateWebhook: Signature validated successfully ✓
[timestamp] UpdateWebhook: Processing event (event: release, action: published)
[timestamp] UpdateWebhook: Handling RELEASE event
[timestamp] UpdateWebhook: handleReleaseEvent STARTED
[timestamp] UpdateWebhook: New release published (version: v1.0.2-test)
[timestamp] UpdateWebhook: Auto-update is enabled, starting update process
[timestamp] UpdateWebhook: Auto-update job dispatched successfully
[timestamp] UpdateWebhook: handleReleaseEvent FINISHED
[timestamp] UpdateWebhook: Processing completed successfully ✓
```

---

### Opção 3: Criar Release no Gitea

1. **Acesse:** `https://git.jf.eng.br/jfeng/GestorStream`
2. **Clique:** Releases → New Release
3. **Preencha:**
   - Tag: `v1.0.2-test`
   - Title: `Teste de Auto-Update com Logs`
4. **Publique**
5. **Verifique logs** (comando acima)

---

## 📊 O QUE ESPERAR AGORA

### ✅ **SE AUTO-UPDATE ESTÁ HABILITADO:**
```
UpdateWebhook: Auto-update is enabled, starting update process
UpdateWebhook: Auto-update job dispatched successfully
```
→ Sistema atualizará automaticamente! 🎉

### ⚠️ **SE AUTO-UPDATE ESTÁ DESABILITADO:**
```
UpdateWebhook: Auto-update is DISABLED
UpdateWebhook: Only updating last_known_version, no auto-update will be performed
UpdateWebhook: recommendation: Enable auto_update_enabled in Gitea settings
```
→ Apenas salva a versão, mas NÃO atualiza automaticamente.

### ❌ **SE SIGNATURE INVÁLIDA:**
```
UpdateWebhook: Invalid Gitea webhook signature
HTTP 401 Unauthorized
```
→ Secret do webhook no Gitea não confere com o secret configurado no sistema.

### ❌ **SE CONFIGURAÇÃO NÃO EXISTE:**
```
✗ NENHUMA configuração do Gitea encontrada no banco!
- Configure em: https://gestor.jf.eng.br/admin/settings (aba Atualizações)
```
→ Precisa configurar no painel admin primeiro.

---

## 🔍 DIAGNÓSTICO DE PROBLEMAS

### Problema: "Nenhum log aparece"

**Possíveis causas:**
1. **Webhook não está sendo enviado pelo Gitea**
   - Verifique: `https://git.jf.eng.br/jfeng/GestorStream/settings/hooks`
   - Clique no webhook → "Recent Deliveries"
   - Veja se há tentativas e qual foi o status

2. **Nginx não está recebendo**
   - Verifique: `sudo grep "/api/webhooks/gitea" /var/log/nginx/access.log | tail -10`
   - Se não houver linhas, o webhook não está chegando no servidor

3. **Laravel não está processando**
   - Verifique: `php artisan route:list | grep gitea`
   - Deve mostrar: `GET|POST|HEAD   api/webhooks/gitea`

---

### Problema: "Auto-update não executa"

**Checklist:**
- [ ] Configuração do Gitea existe no banco? (`GiteaSettings::getActive()`)
- [ ] `auto_update_enabled = true`?
- [ ] `is_active = true`?
- [ ] Webhook Secret configurado corretamente?
- [ ] Evento "Release" marcado no webhook do Gitea?
- [ ] Action do release é "published"? (não "created" ou "draft")

**Verificar:**
```bash
cd /var/www/gestorstream/backend
php artisan tinker --execute="
\$s = \App\Models\GiteaSettings::getActive();
if (\$s) {
    echo 'URL: ' . \$s->gitea_url . PHP_EOL;
    echo 'Repo: ' . \$s->repository . PHP_EOL;
    echo 'Auto-update: ' . (\$s->auto_update_enabled ? 'SIM' : 'NÃO') . PHP_EOL;
    echo 'Ativo: ' . (\$s->is_active ? 'SIM' : 'NÃO') . PHP_EOL;
    echo 'Secret: ' . (empty(\$s->webhook_secret) ? 'NÃO configurado' : 'Configurado') . PHP_EOL;
} else {
    echo 'NENHUMA configuração encontrada!' . PHP_EOL;
}
"
```

---

## ✅ RESUMO DAS MUDANÇAS

| Arquivo | Mudança | Motivo |
|---------|---------|--------|
| `UpdateWebhookController.php` | Adicionados logs detalhados em TODOS os pontos | Permitir diagnóstico completo do fluxo |
| `test-gitea-webhook-complete.sh` | Corrigido para buscar em `GiteaSettings` | Script estava buscando na tabela errada |
| Ambos | Logs estruturados com contexto | Facilitar identificação de problemas |

---

## 🚀 PRÓXIMOS PASSOS

1. **Fazer commit e push das mudanças**
2. **Fazer pull no servidor**
3. **Executar o script de teste**
4. **Criar uma release de teste no Gitea**
5. **Verificar logs em tempo real**

**Agora você terá VISIBILIDADE COMPLETA do que está acontecendo!** 🎉

---

## 📞 SUPORTE

Se mesmo com os logs detalhados o problema persistir, envie:
1. Output completo do script `test-gitea-webhook-complete.sh`
2. Logs do Laravel (`storage/logs/laravel.log`)
3. Screenshot da configuração do webhook no Gitea
4. Screenshot do "Recent Deliveries" do webhook no Gitea
