#!/usr/bin/env bash
# Bring up the hermetic test DB and apply all migrations. Idempotent — safe to re-run.
# Usage: bash e2e/prepare.sh   (from repo root or anywhere)
set -euo pipefail

HERE="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
API="$HERE/../apps/edr-passenger-api"

export DATABASE_URL="postgresql://edr:edr_secret@localhost:5544/edr_database?schema=passenger"
export DATABASE_HOST=localhost DATABASE_PORT=5544 DATABASE_NAME=edr_database
export DATABASE_USER=edr DATABASE_PASSWORD=edr_secret DATABASE_SCHEMA=iam

echo "==> Starting test Postgres (5544) + RabbitMQ (5672)"
docker compose -f "$HERE/docker-compose.yml" up -d

echo "==> Waiting for Postgres healthy"
for i in $(seq 1 30); do
  status="$(docker inspect --format '{{.State.Health.Status}}' edr-passenger-e2e-db 2>/dev/null || echo none)"
  [ "$status" = "healthy" ] && break
  sleep 2
done
[ "${status:-}" = "healthy" ] || { echo "DB did not become healthy"; exit 1; }

echo "==> Prisma migrate deploy (passenger schema)"
( cd "$API" && npx prisma migrate deploy )

echo "==> IAM TypeORM migrations (iam schema)"
( cd "$API" && node scripts/run-iam-migrations.cjs )

echo "==> Prisma client generate"
( cd "$API" && npx prisma generate >/dev/null )

echo "==> Ready. Run:  pnpm --filter @edr/passenger-api test:e2e"
