#!/usr/bin/env bash
# Verify each proposed SendGrid list exists upstream.
# Reads list_ids one-per-line from work/005b_list_ids.txt; writes work/005b_list_verify.tsv.
set -euo pipefail
cd "$HOME/marketing.linderlake.com"
source ./0-config_var_setup.sh

OUT="work/005b_list_verify.tsv"
: > "$OUT"
printf 'list_id\thttp\tname\tcontact_count\n' >> "$OUT"

while IFS= read -r LID; do
  [ -z "$LID" ] && continue
  HTTP="$(curl --connect-timeout 10 --max-time 30 --retry 3 --retry-delay 2 \
    -sS -o /tmp/sg_list.json -w '%{http_code}' \
    -H "Authorization: Bearer $SENDGRID_API_KEY" \
    "https://api.sendgrid.com/v3/marketing/lists/$LID" || echo 000)"
  if [ "$HTTP" = "200" ]; then
    NAME="$(jq -r '.name // ""' /tmp/sg_list.json 2>/dev/null)"
    COUNT="$(jq -r '.contact_count // 0' /tmp/sg_list.json 2>/dev/null)"
  else
    NAME=""
    COUNT=""
  fi
  printf '%s\t%s\t%s\t%s\n' "$LID" "$HTTP" "$NAME" "$COUNT" >> "$OUT"
done < work/005b_list_ids.txt

echo "DONE_LIST_VERIFY"
