#!/usr/bin/env bash
set -euo pipefail

# === Configuración ===
BOT_NAME="PolisplexityBot"
HOST="localhost"
PORT="8011"    # Puerto donde corre tu servidor Django (devserver o Docker mapped)
WEBHOOK_URL="http://${HOST}:${PORT}/bots/webhook/${BOT_NAME}/"
PAYLOAD_FILE="$(dirname "$0")/fake_telegram_update.json"

# === Ejecución ===
echo "=== Test Telegram Webhook ==="
echo "Bot:      $BOT_NAME"
echo "URL:      $WEBHOOK_URL"
echo "Payload:  $PAYLOAD_FILE"
echo

echo "1) Mostrando contenido del payload:"
cat "$PAYLOAD_FILE"
echo

echo "2) Enviando payload al webhook (verbose):"
# Archivo temporal para capturar body
BODY_FILE=$(mktemp)
# Enviamos con curl -v para depuración, guardamos respuesta en BODY_FILE y código en STATUS_CODE
STATUS_CODE=$(curl -v \
  -X POST \
  -H "Content-Type: application/json" \
  --data @"$PAYLOAD_FILE" \
  -o "$BODY_FILE" \
  -w "%{http_code}" \
  "$WEBHOOK_URL" || true)

echo
 echo "→ HTTP Status: $STATUS_CODE"
 echo "→ Response Body:"
 cat "$BODY_FILE"
 echo

if [[ "$STATUS_CODE" != "200" ]]; then
  echo "❌ ERROR: el webhook devolvió código $STATUS_CODE"
  exit 1
fi

echo "3) Verificando en base de datos dentro del contenedor Docker..."
# Usamos docker exec para acceder al entorno con dependencias instaladas
docker exec -i polisplexity_django python manage.py shell << 'EOF'
from pxy_bots.models import TelegramConversation, TelegramMessage

print("Conversations:", TelegramConversation.objects.count())
print("Messages:    ", TelegramMessage.objects.count())
for m in TelegramMessage.objects.all():
    print(f"  • [{m.direction:3}] (conv={m.conversation_id}) rt={m.response_time_ms or 0} ms ⇒ {m.content[:50]!r}")
EOF

# Limpieza temporal
rm -f "$BODY_FILE"

echo "✅ Test completado"
