#!/usr/bin/env bash
# one-command ios e2e: build the release app onto a simulator, bring up the
# db + api, wait for it, run the maestro flows, then tear it all down. wraps
# mobile's e2e:build / e2e:test and the db+api the existing e2e:api brings up,
# minus the blocking foreground server, so `bun run e2e` is a single command.
#
# prerequisites: xcode + a booted ios simulator, maestro on PATH, docker.
set -euo pipefail

ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
API_LOG="${TMPDIR:-/tmp}/crumbs-e2e-api.log"

cleanup() {
  # kill whatever holds the api port (robust against bun --hot's process tree),
  # then drop the containers — the whole run is ephemeral
  lsof -ti:4000 2>/dev/null | xargs kill 2>/dev/null || true
  docker compose -f "$ROOT/docker-compose.yml" down 2>/dev/null || true
}
trap cleanup EXIT

# build + install the release app first: fails fast if the bundle is broken,
# before any infra is spun up
(cd "$ROOT/mobile" && bun run e2e:build)

# db + migrations, then the api in the background (logs tee'd for a failed run)
docker compose -f "$ROOT/docker-compose.yml" up -d --wait
(cd "$ROOT/api" && bun run db:migrate)
# dev routes (login/seed/network) are default-disabled; e2e opts in explicitly
(cd "$ROOT/api" && DEV_ROUTES=true bun run dev) >"$API_LOG" 2>&1 &

# wait for the api to answer before driving the app against it
for _ in $(seq 1 60); do
  curl -sf http://localhost:4000/health >/dev/null 2>&1 && break
  sleep 1
done
curl -sf http://localhost:4000/health >/dev/null 2>&1 || {
  echo "api did not become healthy on :4000 (see $API_LOG)" >&2
  exit 1
}

# drive the built app against the live api
(cd "$ROOT/mobile" && bun run e2e:test)
