#!/bin/bash
# Clears ALL test data from the local API server.
# Preserves superadmin accounts only.
#
# Uses the admin panel auth (separate from regular user auth).
# Default credentials: admin@honeydue.com / password123
#
# Usage:
#   ./cleanup_test_data.sh                       # uses default admin creds
#   ./cleanup_test_data.sh email password         # custom creds

set -euo pipefail

API_BASE="http://127.0.0.1:8000/api"
ADMIN_EMAIL="${1:-admin@honeydue.com}"
ADMIN_PASSWORD="${2:-password123}"

echo "==> Logging into admin panel as '$ADMIN_EMAIL'..."
LOGIN_RESPONSE=$(curl -sf -X POST "$API_BASE/admin/auth/login" \
  -H "Content-Type: application/json" \
  -d "{\"email\": \"$ADMIN_EMAIL\", \"password\": \"$ADMIN_PASSWORD\"}" 2>/dev/null) || {
  echo "ERROR: Could not login to admin panel. Is the backend running at $API_BASE?"
  echo "       Has the admin seed been run? (./dev.sh seed-admin)"
  exit 1
}

TOKEN=$(echo "$LOGIN_RESPONSE" | python3 -c "import sys,json; print(json.load(sys.stdin)['token'])")

echo "==> Clearing all test data..."
CLEAR_RESPONSE=$(curl -sf -X POST "$API_BASE/admin/settings/clear-all-data" \
  -H "Authorization: Bearer $TOKEN" \
  -H "Content-Type: application/json" 2>/dev/null) || {
  echo "ERROR: Clear-all-data failed."
  exit 1
}

USERS_DELETED=$(echo "$CLEAR_RESPONSE" | python3 -c "import sys,json; print(json.load(sys.stdin).get('users_deleted', '?'))")
PRESERVED=$(echo "$CLEAR_RESPONSE" | python3 -c "import sys,json; print(json.load(sys.stdin).get('preserved_users', '?'))")

echo "==> Done! Deleted $USERS_DELETED users, preserved $PRESERVED superadmins."
echo ""
echo "To re-seed test data, run AAA_SeedTests:"
echo "  xcodebuild test -project honeyDue.xcodeproj -scheme HoneyDueUITests \\"
echo "    -sdk iphonesimulator -destination 'platform=iOS Simulator,name=iPhone 17 Pro' \\"
echo "    -only-testing:HoneyDueUITests/AAA_SeedTests"
