#!/bin/bash

# LIMPIEZA BRUTAL - BORRA TODO SIN PREGUNTAR
# Usa jq si está disponible, sino usa grep

API_KEY="SG.E4p-3JJxSk2EIRa4NBFJ8g"

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

# ════════════════════════════════════════════════════════════════
# 1. BORRAR TODOS LOS SINGLE SENDS CON "Campaign_"
# ════════════════════════════════════════════════════════════════

echo "[1/2] Borrando Single Sends..."

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

# Extraer IDs con grep (compatible sin jq)
SEND_IDS=$(echo "$SENDS_JSON" | grep -oP '"id":"?\K[^"]+' | head -100)

DELETED=0
for send_id in $SEND_IDS; do
  # Verificar que tiene "Campaign_" en el nombre (hacer otra llamada o confiar)
  RESULT=$(curl -s -X DELETE -H "Authorization: Bearer $API_KEY" \
    "https://api.sendgrid.com/v3/marketing/singlesends/$send_id" \
    -w "\n%{http_code}")
  
  HTTP_CODE=$(echo "$RESULT" | tail -1)
  
  if [ "$HTTP_CODE" -ge 200 ] && [ "$HTTP_CODE" -lt 300 ]; then
    echo "  ✓ Borrado: $send_id"
    ((DELETED++))
  fi
done

echo "  Total eliminados: $DELETED"
echo ""

# ════════════════════════════════════════════════════════════════
# 2. BORRAR TODAS LAS LISTAS CON "Campaign_LINDERLAKE_Random_"
# ════════════════════════════════════════════════════════════════

echo "[2/2] Borrando Listas..."

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

# Extraer IDs con grep
LIST_IDS=$(echo "$LISTS_JSON" | grep -oP '"id":"?\K[^"]+')

DELETED=0
for list_id in $LIST_IDS; do
  RESULT=$(curl -s -X DELETE -H "Authorization: Bearer $API_KEY" \
    "https://api.sendgrid.com/v3/marketing/lists/$list_id" \
    -w "\n%{http_code}")
  
  HTTP_CODE=$(echo "$RESULT" | tail -1)
  
  if [ "$HTTP_CODE" -ge 200 ] && [ "$HTTP_CODE" -lt 300 ]; then
    echo "  ✓ Borrada: $list_id"
    ((DELETED++))
  fi
done

echo "  Total eliminadas: $DELETED"
echo ""

# ════════════════════════════════════════════════════════════════
# 3. LIMPIAR BD
# ════════════════════════════════════════════════════════════════

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

mysql -u linder8_user -p"$(cat /home/linder8/db_password.txt)" linder8_sendgrid_marketing << EOF
DELETE FROM marketing_lists WHERE list_name LIKE 'Campaign_%' OR list_name LIKE 'Domain_%';
DELETE FROM marketing_campaigns WHERE name LIKE 'Campaign_%';
COMMIT;
EOF

echo "  ✓ BD limpiada"
echo ""

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

