#!/usr/bin/env bash
# POST a batch to the ingestion endpoint and read the per-item results.
set -euo pipefail

: "${TESSERA_API_BASE:?e.g. https://api.staging.tessera.zone/v1}"
: "${TESSERA_INGEST_BASE:?e.g. https://ingest.staging.tessera.zone/v1}"
: "${TESSERA_API_KEY:?your tsk_test_… key}"

NOW="$(date -u +%Y-%m-%dT%H:%M:%SZ)"

# One request, up to 500 events / 5 MiB. The response is per-item: a batch
# with one bad event still lands the other 499.
RESULT="$(curl -sS -X POST "$TESSERA_INGEST_BASE/events" \
  -H "Authorization: Bearer $TESSERA_API_KEY" \
  -H "Content-Type: application/json" \
  -H "Idempotency-Key: docs-http-ingestion-batch" \
  -d '{
    "events": [
      {
        "event_id": "http-0001",
        "entity": {"type": "device", "id": "d_1001"},
        "event_type": "sensor.reading",
        "timestamp": "'"$NOW"'",
        "attributes": {"temperature_c": 21.4, "battery_pct": 88}
      },
      {
        "event_id": "http-0002",
        "entity": {"type": "device", "id": "d_1001"},
        "event_type": "sensor.reading",
        "timestamp": "'"$NOW"'",
        "attributes": {"temperature_c": {"nested": "objects are rejected"}}
      }
    ]
  }')"
printf '%s\n' "$RESULT" | python3 -m json.tool

# Acceptance means durably enqueued; the good event appears on the timeline.
for _ in $(seq 1 30); do
  COUNT="$(curl -sS "$TESSERA_API_BASE/entities/device/d_1001/events" \
    -H "Authorization: Bearer $TESSERA_API_KEY" \
    | python3 -c 'import json,sys; print(len(json.load(sys.stdin)["data"]))')"
  if [ "$COUNT" -ge 1 ]; then break; fi
  sleep 1
done
echo "timeline events for d_1001: $COUNT"
