#!/bin/bash

# LIMPIEZA TOTAL - BORRA TODO DE SENDGRID RELACIONADO A LINDERLAKE

API_KEY="SG.E4p-3JJxSk2EIRa4NBFJ8g"
COMPANY="LINDERLAKE"

echo "════════════════════════════════════════════════════════════"
echo "LIMPIEZA TOTAL - BORRANDO BASURA DE SENDGRID"
echo "════════════════════════════════════════════════════════════"
echo ""

# 1. BORRAR SINGLE SENDS
echo "1. Borrando Single Sends..."

SENDS=$(curl -s -H "Authorization: Bearer $API_KEY" \
  "https://api.sendgrid.com/v3/marketing/singlesends?page_size=500" | \
  jq -r '.result[] | select(.name | contains("Campaign_")) | .id')

SEND_COUNT=$(echo "$SENDS" | grep -c ".")

if [ -z "$SENDS" ]; then
  echo "   ✓ Sin Single Sends para borrar"
else
  echo "   Encontrados: $SEND_COUNT"
  for send_id in $SENDS; do
    curl -s -X DELETE -H "Authorization: Bearer $API_KEY" \
      "https://api.sendgrid.com/v3/marketing/singlesends/$send_id" > /dev/null
    echo "   ✓ Borrado: $send_id"
  done
fi

echo ""

# 2. BORRAR LISTAS
echo "2. Borrando Listas..."

LISTS=$(curl -s -H "Authorization: Bearer $API_KEY" \
  "https://api.sendgrid.com/v3/marketing/lists?page_size=500" | \
  jq -r '.result[] | select(.name | contains("Campaign_LINDERLAKE_Random_")) | .id')

LIST_COUNT=$(echo "$LISTS" | grep -c ".")

if [ -z "$LISTS" ]; then
  echo "   ✓ Sin listas para borrar"
else
  echo "   Encontradas: $LIST_COUNT"
  for list_id in $LISTS; do
    curl -s -X DELETE -H "Authorization: Bearer $API_KEY" \
      "https://api.sendgrid.com/v3/marketing/lists/$list_id" > /dev/null
    echo "   ✓ Borrada: $list_id"
  done
fi

echo ""
echo "════════════════════════════════════════════════════════════"
echo "✅ LIMPIEZA COMPLETADA"
echo "════════════════════════════════════════════════════════════"

