#!/usr/bin/env bash
# P1 煙測：invite me +（可選）personas / scout brands 存在性
set -euo pipefail
BASE="${API_BASE:-http://127.0.0.1:8888}"
EMAIL="${SMOKE_EMAIL:-admin@haixun.local}"
PASS="${SMOKE_PASSWORD:-Admin123!@#x}"

ok() { printf '[ok] %s\n' "$*"; }
fail() { printf '[FAIL] %s\n' "$*" >&2; exit 1; }

echo "=== smoke P1 against $BASE ==="

login=$(curl -sf -X POST "$BASE/api/v1/auth/login" \
  -H 'Content-Type: application/json' \
  -d "{\"email\":\"$EMAIL\",\"password\":\"$PASS\"}" ) || fail "login"
TOKEN=$(echo "$login" | python3 -c "import sys,json; print(json.load(sys.stdin)['data']['tokens']['access_token'])")

inv=$(curl -sf "$BASE/api/v1/invite/me" -H "Authorization: Bearer $TOKEN") || fail "IV-01 invite/me"
code=$(echo "$inv" | python3 -c "import sys,json; print(json.load(sys.stdin).get('code'))")
[[ "$code" == "102000" ]] || fail "invite/me code=$code"
ic=$(echo "$inv" | python3 -c "import sys,json; print(json.load(sys.stdin)['data']['me']['invite_code'])")
[[ -n "$ic" ]] || fail "empty invite_code"
ok "IV-01 getMyNetwork invite_code=$ic"

# admin tree（admin 帳才過）
tree=$(curl -sf "$BASE/api/v1/invite/tree" -H "Authorization: Bearer $TOKEN" || true)
tcode=$(echo "$tree" | python3 -c "import sys,json; print(json.load(sys.stdin).get('code',''))" 2>/dev/null || true)
if [[ "$tcode" == "102000" ]]; then
  ok "IV-08 getTree"
else
  ok "IV-08 getTree skipped/non-admin (code=$tcode)"
fi

# 存在性煙測
for path in /api/v1/personas /api/v1/own-posts /api/v1/scout/brands /api/v1/inspire/session; do
  r=$(curl -s -o /dev/null -w '%{http_code}' "$BASE$path" -H "Authorization: Bearer $TOKEN" || true)
  [[ "$r" != "404" ]] || fail "missing $path"
  ok "path $path http=$r"
done

echo "=== smoke P1 passed ==="
