#!/usr/bin/env bash
# Pull the published backend image and run it (+ a throwaway DB) for the frontend's
# integration tests, or for local dev. The frontend's api_client then makes real HTTP
# to it instead of importing backend source.
#
#   scripts/backend-for-tests.sh up     # pull + start, wait until healthy, print base URL
#   scripts/backend-for-tests.sh down   # stop + remove (incl. the throwaway db volume)
#   scripts/backend-for-tests.sh url    # print the base URL (no lifecycle change)
#
# Which backend build: THERMOGRAPH_BACKEND_TEST_TAG (default a published tag; set a
# sha-<12hex> to pin one). Host port: BACKEND_TEST_HOST_PORT (default 18137).
set -euo pipefail
cd "$(dirname "$0")/.."

export POSTGRES_PASSWORD="${POSTGRES_PASSWORD:-testing}"
export BACKEND_TEST_HOST_PORT="${BACKEND_TEST_HOST_PORT:-18137}"
BASE_URL="http://127.0.0.1:${BACKEND_TEST_HOST_PORT}"
COMPOSE=(docker compose -f docker-compose.test.yml)

case "${1:-up}" in
  up)
    echo "==> pulling backend image (${THERMOGRAPH_BACKEND_TEST_TAG:-v0.0.2-split-ci})" >&2
    "${COMPOSE[@]}" pull backend >&2
    echo "==> starting backend + db" >&2
    "${COMPOSE[@]}" up -d >&2
    echo "==> waiting for backend /healthz (up to 90s)" >&2
    for _ in $(seq 1 45); do
      curl -fsS -o /dev/null "$BASE_URL/healthz" 2>/dev/null && { echo "$BASE_URL"; exit 0; }
      sleep 2
    done
    echo "!! backend never became healthy" >&2
    "${COMPOSE[@]}" logs --tail=40 backend >&2
    exit 1
    ;;
  down)
    "${COMPOSE[@]}" down -v --remove-orphans >/dev/null 2>&1 || true
    echo "==> backend stopped" >&2
    ;;
  url)
    echo "$BASE_URL"
    ;;
  *)
    echo "usage: $0 {up|down|url}" >&2; exit 2 ;;
esac
