#!/usr/bin/env bash
# BigQuery connector: create the source, test the connection, first sync.
# Requires a real BigQuery table (hosted runs only, not the local stack): set
# TESSERA_BQ_PROJECT / TESSERA_BQ_DATASET / TESSERA_BQ_TABLE.
set -euo pipefail

: "${TESSERA_API_BASE:?e.g. https://api.staging.tessera.zone/v1}"
: "${TESSERA_API_KEY:?your tsk_test_… key}"
: "${TESSERA_BQ_PROJECT:?customer GCP project}"
: "${TESSERA_BQ_DATASET:?BigQuery dataset id}"
: "${TESSERA_BQ_TABLE:?table id}"
AUTH=(-H "Authorization: Bearer $TESSERA_API_KEY")

# cross_project_grant: no stored credential — you grant Tessera's per-project
# service account dataViewer on the dataset + readSessionUser on the project.
SOURCE="$(curl -sS -X POST "$TESSERA_API_BASE/sources" "${AUTH[@]}" \
  -H "Content-Type: application/json" \
  -H "Idempotency-Key: docs-bigquery-source" \
  -d '{
    "name": "warehouse-events",
    "kind": "bigquery",
    "config": {
      "gcp_project": "'"$TESSERA_BQ_PROJECT"'",
      "dataset": "'"$TESSERA_BQ_DATASET"'",
      "table": "'"$TESSERA_BQ_TABLE"'",
      "auth_mode": "cross_project_grant"
    }
  }')"
SOURCE_ID="$(printf '%s' "$SOURCE" | python3 -c 'import json,sys; print(json.load(sys.stdin)["source_id"])')"

# The checks name the exact missing IAM grant on failure.
curl -sS -X POST "$TESSERA_API_BASE/sources/$SOURCE_ID/test-connection" "${AUTH[@]}" \
  | python3 -c '
import json, sys
result = json.load(sys.stdin)
print("test-connection:", result["status"])
for check in result["checks"]:
    print("  %s: %s" % (check["name"], check["status"]))
'

SYNC="$(curl -sS -X POST "$TESSERA_API_BASE/sources/$SOURCE_ID/syncs" "${AUTH[@]}" \
  -H "Content-Type: application/json" \
  -H "Idempotency-Key: docs-bigquery-first-sync" \
  -d '{"mode": "full"}')"
SYNC_ID="$(printf '%s' "$SYNC" | python3 -c 'import json,sys; print(json.load(sys.stdin)["sync_id"])')"
for _ in $(seq 1 600); do
  STATUS="$(curl -sS "$TESSERA_API_BASE/syncs/$SYNC_ID" "${AUTH[@]}" \
    | python3 -c 'import json,sys; print(json.load(sys.stdin)["status"])')"
  if [ "$STATUS" = "succeeded" ] || [ "$STATUS" = "failed" ]; then break; fi
  sleep 1
done
echo "first sync: $STATUS"
