#!/usr/bin/env bash
# One-command UI E2E: infra → build → boot app tier (via Playwright webServer) → seed+auth → run →
# open the HTML report. Idempotent; reuses an already-running stack. Any args pass through to
# playwright (e.g. `bash e2e-ui/run.sh --project=portal ua1`).
set -euo pipefail

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

echo "==> 1/4 Infra: Postgres (5544) + RabbitMQ (5672) + migrations"
bash "$ROOT/e2e/prepare.sh"
echo "    waiting for RabbitMQ healthy"
for _ in $(seq 1 30); do
  s="$(docker inspect --format '{{.State.Health.Status}}' edr-passenger-e2e-rmq 2>/dev/null || echo none)"
  [ "$s" = "healthy" ] && break; sleep 2
done

echo "==> 2/4 Build shared types (@edr/types dist — nest build needs it)"
pnpm --filter @edr/types build >/dev/null

echo "==> 3/4 Ensure passenger-api dev env (test DB 5544, port 4000, brokers/Fayda off, seeding on)"
if [ ! -f "$API/.env" ]; then
  sed -e 's/^PORT=.*/PORT=4000/' \
      -e 's/^SEED_EDR_PASSENGER_ORG=.*/SEED_EDR_PASSENGER_ORG=true/' \
      -e 's/^SEED_PASSENGER_STAFF=.*/SEED_PASSENGER_STAFF=true/' \
      "$API/.env.test" > "$API/.env"
  echo "    created $API/.env"
fi

echo "==> 4/4 Playwright (boots api/portal/backoffice if not already up, seeds + mints auth, runs)"
npx playwright test -c "$HERE/playwright.config.ts" "$@" || TEST_EXIT=$?

REPORT="$ROOT/e2e-ui-report/index.html"
if [ -f "$REPORT" ]; then
  echo "==> Report: $REPORT"
  open "$REPORT" 2>/dev/null || true
fi
exit "${TEST_EXIT:-0}"
