#!/usr/bin/env bash
# T-02 "Build a social app backend" — the assembled driver.
# Runs every checkpoint end to end against the local stack.
# Usage:  source /tmp/inaya_env.sh && export INAYA_LABS_ENVIRONMENT=local
#         bash InayaLabs-website/docs-src/tutorials/_code/social-app-backend/social_app.sh
set -euo pipefail

: "${INAYA_LABS_API_KEY:?source /tmp/inaya_env.sh first}"
INAYA_API_KEY="${INAYA_LABS_API_KEY}"
INAYA_APP_KEY="${INAYA_LABS_APP_KEY}"
TENANT_ID="${TENANT_ID:-playground_a43b973c77e94b7f8b0e64d96c86edf8}"
AUTH_URL="${AUTH_URL:-http://127.0.0.1:40004}"
USQ_URL="${USQ_URL:-http://127.0.0.1:40170}"
USC_URL="${USC_URL:-http://127.0.0.1:40171}"
FDC_URL="${FDC_URL:-http://127.0.0.1:40167}"
FDQ_URL="${FDQ_URL:-http://127.0.0.1:40168}"
MSC_URL="${MSC_URL:-http://127.0.0.1:40163}"
MSQ_URL="${MSQ_URL:-http://127.0.0.1:40164}"
KEYS=(-H "x-api-key: ${INAYA_API_KEY}" -H "x-client-app-key: ${INAYA_APP_KEY}")

sign_in() {
  curl -sf -X POST "${AUTH_URL}/v3/auth/qa/login" "${KEYS[@]}" \
    -H "Content-Type: application/json" \
    -d "{\"device_id\": \"t02-device-01\", \"locale\": \"en-US\", \"tenant_id\": \"${TENANT_ID}\", \"username\": \"$1\"}" \
    | python3 -c 'import json,sys; d=json.load(sys.stdin); print(d["token"], d["user"]["id"])'
}
echo "═══ T-02 social app backend · tenant ${TENANT_ID} ═══"

# 1. two residents sign in
read PRIYA_T PRIYA_U <<< "$(sign_in t02-priya)"
read OMAR_T  OMAR_U  <<< "$(sign_in t02-omar)"
echo "✔ checkpoint 1 — two identities signed in"

# 2. omar's profile: born empty, fleshed out, discovered
curl -sf "${USQ_URL}/v3/users/${OMAR_U}" -H "Authorization: Bearer ${OMAR_T}" "${KEYS[@]}" > /tmp/t02-omar.json
python3 - <<'EOF'
import json
me = json.load(open("/tmp/t02-omar.json"))
me.update(first_name="Omar", last_name="Haddad", display_name="Omar H.",
          bio="Plot 14 — tomatoes and one very opinionated rooster.",
          location_display_name="North Garden",
          profile_json={"plot": 14, "skills": ["irrigation", "compost"]})
json.dump(me, open("/tmp/t02-omar-updated.json", "w"))
EOF
curl -sf -o /dev/null -X PUT "${USC_URL}/v3/users/${OMAR_U}" \
  -H "Authorization: Bearer ${OMAR_T}" "${KEYS[@]}" \
  -H "Content-Type: application/json" --data-binary @/tmp/t02-omar-updated.json
echo "✔ checkpoint 2 — omar's profile updated"

# 3. feed: post + reply, poll until published, search
POST_ID=$(curl -s -X POST "${FDC_URL}/v3/feed/post" \
  -H "Authorization: Bearer ${PRIYA_T}" "${KEYS[@]}" \
  -H "Content-Type: application/json" \
  -d '{"content": "Seedling swap this Saturday at the tool shed — bring extras.", "languageCode": "en-US", "userHashtags": ["seedling-swap"], "mediaFiles": []}' \
  | python3 -c 'import json,sys; print(json.load(sys.stdin))')
curl -sf -o /dev/null -X POST "${FDC_URL}/v3/feed/reply" \
  -H "Authorization: Bearer ${OMAR_T}" "${KEYS[@]}" \
  -H "Content-Type: application/json" \
  -d "{\"parentId\": \"${POST_ID}\", \"content\": \"Saving two trays of Roma tomatoes for you.\", \"languageCode\": \"en-US\", \"userHashtags\": [], \"mediaFiles\": []}"
for i in $(seq 1 36); do
  curl -sf "${FDQ_URL}/v3/feed?page=1&page_size=10" -H "Authorization: Bearer ${OMAR_T}" "${KEYS[@]}" \
    | grep -q "${POST_ID}" && { echo "✔ checkpoint 3 — feed published after ${i} poll(s)"; break; }
  sleep 5
done

# 4. DMs: conversation, message, receipts
CONV_BODY=$(printf '{"otherParticipants": ["%s"], "title": "Seedling swap"}' "${PRIYA_U}")
CID=$(curl -sf -X POST "${MSC_URL}/v3/messaging/conversations" \
  -H "Authorization: Bearer ${OMAR_T}" "${KEYS[@]}" \
  -H "Content-Type: application/json" -d "${CONV_BODY}" \
  | python3 -c 'import json,sys; print(json.load(sys.stdin)["id"])')
MSG_BODY=$(printf '{"conversationId": "%s", "content": "Could I get three of the Roma trays?", "mediaUrls": []}' "${CID}")
MID=$(curl -sf -X POST "${MSC_URL}/v3/messaging/messages" \
  -H "Authorization: Bearer ${OMAR_T}" "${KEYS[@]}" \
  -H "Content-Type: application/json" -d "${MSG_BODY}" \
  | python3 -c 'import json,sys; print(json.load(sys.stdin)["id"])')
for i in $(seq 1 36); do
  curl -sf "${MSQ_URL}/v3/messaging/conversations/${CID}/messages?page=1&page_size=10" \
    -H "Authorization: Bearer ${PRIYA_T}" "${KEYS[@]}" \
    | grep -q "Roma trays" && break
  sleep 5
done
curl -sf -o /dev/null -X POST "${MSC_URL}/v3/messaging/messages/${MID}/read-receipts" \
  -H "Authorization: Bearer ${PRIYA_T}" "${KEYS[@]}"
echo "✔ checkpoint 4 — DM published and read"

# 5. failure injection: feed pipeline down, then recover
pkill -x feed-workflow-service && echo "   feed-workflow killed"
STALL_ID=$(curl -s -X POST "${FDC_URL}/v3/feed/post" \
  -H "Authorization: Bearer ${PRIYA_T}" "${KEYS[@]}" \
  -H "Content-Type: application/json" \
  -d '{"content": "STALL TEST: rain moved the swap to Sunday.", "languageCode": "en-US", "userHashtags": ["seedling-swap"], "mediaFiles": []}' \
  | python3 -c 'import json,sys; print(json.load(sys.stdin))')
sleep 12
if curl -sf "${FDQ_URL}/v3/feed?page=1&page_size=20" -H "Authorization: Bearer ${OMAR_T}" "${KEYS[@]}" | grep -q "${STALL_ID}"; then
  echo "unexpected: stalled post was visible"; exit 1
fi
echo "✔ checkpoint 5a — read side quiet while pipeline down"
source /tmp/inaya_env.sh; export INAYA_LABS_ENVIRONMENT=local
nohup "$(cd "$(dirname "$0")/../../../../.." && pwd)/target/debug/feed-workflow-service" > /tmp/feed-workflow-service.log 2>&1 &
for i in $(seq 1 60); do
  curl -sf "${FDQ_URL}/v3/feed?page=1&page_size=20" -H "Authorization: Bearer ${OMAR_T}" "${KEYS[@]}" \
    | grep -q "${STALL_ID}" && { echo "✔ checkpoint 5b — queued post drained after restart (poll ${i})"; break; }
  sleep 5
done

echo "═══ T-02 complete ═══"
