#!/usr/bin/env bash
# One-shot E2E: ensure Docker is up → start the test DB + migrations → run all suites → open the
# HTML dashboard. Safe to re-run. The DB is left running for fast subsequent runs unless --down.
#
#   bash e2e/run.sh            # run everything, leave the DB up, open the report
#   bash e2e/run.sh --down     # same, but tear the DB down afterwards
#   bash e2e/run.sh --no-open  # don't auto-open the browser (just print the path)
set -euo pipefail

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

DOWN=0; OPEN=1
for arg in "$@"; do
  case "$arg" in
    --down) DOWN=1 ;;
    --no-open) OPEN=0 ;;
    *) echo "unknown flag: $arg" >&2; exit 2 ;;
  esac
done

# 1. Ensure the Docker daemon is running (start Docker Desktop on macOS if needed).
if ! docker info >/dev/null 2>&1; then
  echo "==> Docker daemon not running; attempting to start Docker Desktop…"
  open -a Docker 2>/dev/null || { echo "Could not launch Docker. Start it manually and re-run."; exit 1; }
  printf "    waiting for Docker"
  for _ in $(seq 1 40); do
    if docker info >/dev/null 2>&1; then echo " — up"; break; fi
    printf "."; sleep 2
  done
  docker info >/dev/null 2>&1 || { echo; echo "Docker did not start in time."; exit 1; }
fi

# 2. Bring up the test DB + apply migrations (idempotent).
bash "$HERE/prepare.sh"

# 3. Run all suites (this also writes the HTML report via the jest-html-reporters config).
#    Don't let a test failure abort the script — we still want to open the report.
set +e
( cd "$API" && npx jest --config ./test/jest-e2e.json )
JEST_EXIT=$?
set -e

# 4. Open (or print) the report.
if [ -f "$REPORT" ]; then
  if [ "$OPEN" -eq 1 ]; then
    echo "==> Opening report: $REPORT"
    open "$REPORT" 2>/dev/null || echo "    (open it manually: $REPORT)"
  else
    echo "==> Report written: $REPORT"
  fi
else
  echo "!! No report generated (tests may have failed to run)."
fi

# 5. Optional teardown.
if [ "$DOWN" -eq 1 ]; then
  echo "==> Tearing down the test DB"
  docker compose -f "$HERE/docker-compose.yml" down
fi

exit "$JEST_EXIT"
