#!/bin/bash

# LIMPIEZA BRUTAL V2 - SIN PEDIR PASSWORD
# Borra TODO de SendGrid (Single Sends + Listas) + BD

API_KEY="SG.E4p-3JJxSk2EIRa4NBFJ8g"
DB_USER="linder8_user"
DB_PASS="linder8_sendgrid_marketing"  # Esta es la BD, no el password
DB_NAME="linder8_sendgrid_marketing"

echo ""
echo "════════════════════════════════════════════════════════════"
echo "LIMPIEZA BRUTAL V2 - BORRANDO TODA LA BASURA"
echo "════════════════════════════════════════════════════════════"
echo ""

# ════════════════════════════════════════════════════════════════
# 1. BORRAR TODOS LOS SINGLE SENDS
# ════════════════════════════════════════════════════════════════

echo "[1/3] Obteniendo Single Sends..."

SENDS_JSON=$(curl -s -H "Authorization: Bearer $API_KEY" \
  "https://api.sendgrid.com/v3/marketing/singlesends?page_size=500")

echo "$SENDS_JSON" > /tmp/sends.json

# Contar cuántos hay
SEND_COUNT=$(echo "$SENDS_JSON" | grep -o '"id"' | wc -l)
echo "  Encontrados: $SEND_COUNT"

if [ "$SEND_COUNT" -gt 0 ]; then
  echo "  Borrando..."
  
  # Extraer IDs con grep/sed
  echo "$SENDS_JSON" | grep -oP '"id":"?\K[^"]+' | while read send_id; do
    curl -s -X DELETE -H "Authorization: Bearer $API_KEY" \
      "https://api.sendgrid.com/v3/marketing/singlesends/$send_id" > /dev/null 2>&1
    echo "    ✓ Borrado: $send_id"
  done
fi

echo ""

# ════════════════════════════════════════════════════════════════
# 2. BORRAR TODAS LAS LISTAS
# ════════════════════════════════════════════════════════════════

echo "[2/3] Obteniendo Listas..."

LISTS_JSON=$(curl -s -H "Authorization: Bearer $API_KEY" \
  "https://api.sendgrid.com/v3/marketing/lists?page_size=500")

echo "$LISTS_JSON" > /tmp/lists.json

# Contar cuántas hay
LIST_COUNT=$(echo "$LISTS_JSON" | grep -o '"id"' | wc -l)
echo "  Encontradas: $LIST_COUNT"

if [ "$LIST_COUNT" -gt 0 ]; then
  echo "  Borrando..."
  
  # Extraer IDs
  echo "$LISTS_JSON" | grep -oP '"id":"?\K[^"]+' | while read list_id; do
    curl -s -X DELETE -H "Authorization: Bearer $API_KEY" \
      "https://api.sendgrid.com/v3/marketing/lists/$list_id" > /dev/null 2>&1
    echo "    ✓ Borrada: $list_id"
  done
fi

echo ""

# ════════════════════════════════════════════════════════════════
# 3. LIMPIAR BD (sin password porque no lo necesitamos aquí)
# ════════════════════════════════════════════════════════════════

echo "[3/3] Limpiando BD..."

# Usar .my.cnf o conexión sin password si existe
mysql -u linder8_user linder8_sendgrid_marketing << EOFMYSQL 2>/dev/null
DELETE FROM marketing_lists WHERE 1=1;
DELETE FROM marketing_campaigns WHERE 1=1;
COMMIT;
EOFMYSQL

if [ $? -eq 0 ]; then
  echo "  ✓ BD limpiada"
else
  echo "  ⚠️  No se pudo limpiar BD (intenta manualmente o con tu password)"
fi

echo ""

echo "════════════════════════════════════════════════════════════"
echo "✅ LIMPIEZA COMPLETA"
echo "════════════════════════════════════════════════════════════"
echo ""

