#!/usr/bin/env bash
# Overdue follow-up nudge
# Sends a templated email to every lead whose follow-up date has passed. Runs a dry run first and refuses to send unless you pass --send, because the failure mode here is emailing your whole pipeline by accident.
#
# Category : Operations
# Safety   : WRITES DATA, read before running
# Uses     : leads list, leads send-email, email-templates list
# Returns  : A merged dry-run preview, then the sends once you confirm.
#
# Requires the SendSquared CLI and jq:
#   curl -fsSL https://cli.sendsquared.com/install.sh | bash
#   sendsquared auth login
#
# Free to use and adapt. https://sendsquared.com/cli/scripts/#followup-nudge

# Usage: ./followup-nudge.sh <templateId> [--send]
# Without --send this only previews. That default is deliberate.
set -euo pipefail
TEMPLATE=${1:?pass a template id, see: sendsquared email-templates list}
CONFIRM=${2:-}
TODAY=$(date -u +%F)

IDS=$(
  sendsquared leads list --limit 100 \
  | jq -r --arg today "$TODAY" '
      .data[]
      | select((.archived // false) | not)
      | select((.followupAt // "") != "")
      | select((.followupAt | split("T")[0]) < $today)
      | .id
    ' | tr '\n' ' '
)

[ -z "${IDS// /}" ] && { echo "nothing overdue"; exit 0; }
echo "overdue leads: $IDS"

echo "--- dry run"
sendsquared leads send-email $IDS --template "$TEMPLATE" --dry-run

if [ "$CONFIRM" = "--send" ]; then
  echo "--- sending"
  sendsquared leads send-email $IDS --template "$TEMPLATE"
else
  echo
  echo "Preview only. Re-run with --send once the merge above looks right."
fi
