#!/usr/bin/env bash
# Smoke-test graph session ingest + dashboard API.
#
#   ./scripts/test_graphs_api.sh
#   GRAPHS_BASE=http://localhost:8080/app/androidcast_project/graphs CRASH_USER=admin CRASH_PASS=admin ./scripts/test_graphs_api.sh
#   COOKIE='ac_crash_sess=…' GRAPHS_BASE=https://apps.f0xx.org/app/androidcast_project/graphs ./scripts/test_graphs_api.sh
set -euo pipefail

CRASH_BASE="${CRASH_BASE:-http://127.0.0.1:8080/app/androidcast_project/crashes}"
GRAPHS_BASE="${GRAPHS_BASE:-${CRASH_BASE/\/crashes\//\/graphs\/}}"
UPLOAD_URL="${GRAPHS_BASE}/api/graph_upload.php"
API_URL="${GRAPHS_BASE}/api/graphs.php"
COOKIE_JAR="${TMPDIR:-/tmp}/graph_api_cookies_$$.txt"
trap 'rm -f "$COOKIE_JAR"' EXIT

CURL_AUTH=()
if [[ -n "${COOKIE:-}" ]]; then
  CURL_AUTH=(-H "Cookie: ${COOKIE}")
else
  user="${CRASH_USER:-admin}"
  pass="${CRASH_PASS:-admin}"
  curl -sS -c "$COOKIE_JAR" -b "$COOKIE_JAR" -X POST \
    -d "username=${user}&password=${pass}" \
    "${CRASH_BASE}/login" -o /dev/null
  CURL_AUTH=(-b "$COOKIE_JAR")
fi

now_ms="$(date +%s)000"
start_ms=$((now_ms - 600000))
sid="smoke-graph-$(date +%s)"

payload="$(cat <<EOF
{
  "schema_version": 1,
  "ingest_kind": "graph_session",
  "session_id": "${sid}",
  "company_id": 1,
  "user_id": 1,
  "device_id": "smoke-device-01",
  "app_version": "0.1.0-smoke",
  "sdk_int": 34,
  "started_at_epoch_ms": ${start_ms},
  "ended_at_epoch_ms": ${now_ms},
  "duration_s": 600,
  "completed": true,
  "direction": "sender",
  "transport": "wifi",
  "avg_kbps": 4200,
  "recv_kbps": 800,
  "packet_loss_pct": 0.4,
  "ntp_source": "backend",
  "ntp_correction_s": 2,
  "install_source": "ota",
  "meta": {"smoke": true}
}
EOF
)"

echo "POST ${UPLOAD_URL}"
upload_code="$(curl -sS -o /tmp/graph_upload_resp.json -w '%{http_code}' \
  "${CURL_AUTH[@]}" \
  -H 'Content-Type: application/json' \
  -d "${payload}" \
  "${UPLOAD_URL}")"
echo "upload HTTP ${upload_code}"
cat /tmp/graph_upload_resp.json
echo

echo "GET ${API_URL}?days=7"
graphs_code="$(curl -sS -o /tmp/graphs_resp.json -w '%{http_code}' \
  "${CURL_AUTH[@]}" \
  "${API_URL}?days=7")"
echo "graphs HTTP ${graphs_code}"
head -c 400 /tmp/graphs_resp.json
echo
echo "…"

if [[ "${upload_code}" != "200" ]]; then
  echo "FAIL: upload expected 200" >&2
  exit 1
fi
if [[ "${graphs_code}" != "200" ]]; then
  echo "FAIL: graphs API expected 200 (got ${graphs_code})" >&2
  exit 1
fi
if ! grep -q '"ok":true' /tmp/graphs_resp.json; then
  echo "FAIL: graphs API body missing ok:true" >&2
  exit 1
fi
echo "OK"
