#!/bin/bash

echo "========================================="
echo "TESTE MANUAL DO WEBHOOK"
echo "========================================="
echo ""

# Obter o webhook secret
cd /var/www/gestorstream/backend
SECRET=$(php artisan tinker --execute="echo \App\Models\GiteaSettings::getActive()->webhook_secret ?? 'NO_SECRET';")

echo "Webhook Secret: ${SECRET:0:10}..."
echo ""

# Criar payload de teste
PAYLOAD='{
  "action": "published",
  "release": {
    "tag_name": "v1.0.1",
    "name": "Test Release",
    "body": "This is a test release",
    "draft": false,
    "prerelease": false,
    "published_at": "2026-01-12T14:00:00Z"
  },
  "repository": {
    "full_name": "jfeng/GestorStream"
  },
  "sender": {
    "login": "jfeng"
  }
}'

# Calcular assinatura (HMAC SHA-256)
SIGNATURE=$(echo -n "$PAYLOAD" | openssl dgst -sha256 -hmac "$SECRET" | awk '{print $2}')

echo "Payload:"
echo "$PAYLOAD" | jq .
echo ""

echo "Signature: $SIGNATURE"
echo ""

# Enviar requisição
echo "Enviando requisição para o webhook..."
echo ""

RESPONSE=$(curl -s -w "\nHTTP_CODE:%{http_code}" \
  -X POST \
  -H "Content-Type: application/json" \
  -H "X-Gitea-Event: release" \
  -H "X-Gitea-Signature: $SIGNATURE" \
  -d "$PAYLOAD" \
  https://gestor.jf.eng.br/api/v1/webhooks/gitea)

HTTP_CODE=$(echo "$RESPONSE" | grep "HTTP_CODE:" | cut -d: -f2)
BODY=$(echo "$RESPONSE" | grep -v "HTTP_CODE:")

echo "HTTP Status: $HTTP_CODE"
echo "Response:"
echo "$BODY" | jq . 2>/dev/null || echo "$BODY"
echo ""

# Verificar logs
echo "Verificando logs do Laravel (últimas 20 linhas com 'webhook')..."
tail -50 /var/www/gestorstream/backend/storage/logs/laravel.log | grep -i "webhook\|gitea\|release" | tail -20
echo ""

echo "========================================="
echo "TESTE COMPLETO"
echo "========================================="
