#!/usr/bin/env bash
# Reservation audit
# The one built for Wilderness. Walks every reservation and flags the ones that will quietly break automations: no guest attached, no email, no phone, or a stay with no unit.
#
# Category : Data hygiene
# Safety   : read only
# Uses     : reservations list, reservations count
# Returns  : Counts by defect plus a CSV of every reservation that needs attention.
#
# 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/#reservation-audit

# Reservations that will silently break automations.
#
# Bounded by default. A full portfolio can run to hundreds of thousands of
# stays, and walking all of them takes long enough that nobody runs the script
# twice. PAGES=0 removes the cap when you do want the whole history.
set -euo pipefail

PAGES=${1:-20}   # 20 pages x 1000 = the 20k most recent stays; 0 = everything
OUT=reservation-audit-$(date +%F).csv
echo "id,reservation_number,arrival,issue" > "$OUT"
BEFORE=""
SEEN=0
PAGENO=0

while :; do
  PAGENO=$((PAGENO+1))
  if [ "$PAGES" -ne 0 ] && [ "$PAGENO" -gt "$PAGES" ]; then break; fi
  PAGE=$(sendsquared reservations list --limit 1000 ${BEFORE:+--before "$BEFORE"})
  COUNT=$(jq '.data | length' <<<"$PAGE")
  [ "$COUNT" -eq 0 ] && break

  jq -r '
    .data[]
    | . as $r
    | [ (if $r.contact_id == null then "no guest attached" else empty end),
        (if ($r.contact.primaryEmail // "") == "" then "no email" else empty end),
        (if (($r.contact.mobile_phone // "") == "" and ($r.contact.home_phone // "") == "") then "no phone" else empty end),
        (if (($r.units // []) | length) == 0 then "no unit" else empty end),
        (if ($r.arrival_date // "") == "" then "no arrival date" else empty end) ]
    | .[] as $issue
    | [ $r.id, ($r.reservation_number // ""), (($r.arrival_date // "") | split("T")[0]), $issue ]
    | @csv
  ' <<<"$PAGE" >> "$OUT"

  BEFORE=$(jq -r '[.data[].id] | min' <<<"$PAGE")
  SEEN=$((SEEN+COUNT))
  [ "$COUNT" -lt 1000 ] && break
done

TOTAL=$(tail -n +2 "$OUT" | wc -l | tr -d ' ')
echo "--- scanned $SEEN reservations, $TOTAL findings"
tail -n +2 "$OUT" | sed 's/.*,"\(.*\)"$/\1/' | sort | uniq -c | sort -rn | sed 's/^/  /'
echo "--- full list: $OUT"
