#!/usr/bin/env bash
# Force every mitra offline on the target backend. Used as a pre-step for tests
# that verify the "no bestie available" disabled-CTA state.
#
# Reads BACKEND_INTERNAL_URL and a CC_JWT from the shell env (NOT from
# .maestro/config.yaml — CC credentials should never be committed).
#
# Usage:
#   CC_JWT=<token> bash client_app/.maestro/scripts/force_all_mitras_offline.sh

set -euo pipefail

: "${BACKEND_INTERNAL_URL:=http://192.168.88.247:3001}"
: "${CC_JWT:?CC_JWT must be set (a valid control_center user JWT)}"

# Get the list of currently online mitras from the CC dashboard endpoint.
mitras=$(curl -fsSL "$BACKEND_INTERNAL_URL/internal/mitra-online-status" \
  -H "Authorization: Bearer $CC_JWT" \
  | jq -r '.data[] | select(.is_online == true) | .mitra_id')

if [ -z "$mitras" ]; then
  echo "All mitras already offline."
  exit 0
fi

for mitra_id in $mitras; do
  echo "Forcing $mitra_id offline..."
  curl -fsSL -X POST "$BACKEND_INTERNAL_URL/internal/mitra-online-status/$mitra_id/offline" \
    -H "Authorization: Bearer $CC_JWT" \
    -H "Content-Type: application/json" \
    -d '{}' || echo "  (failed — endpoint may not exist; check route name)"
done

echo "Done."
