#!/usr/bin/env bash
# Run the end-to-end tests against the local dev stack.
#
#   bin/e2e                      # every test
#   bin/e2e trendline            # only files matching a name
#
# They run inside the `playwright` compose service, which already has
# Playwright and a browser. Nothing is installed into this repo — NODE_PATH
# points Node at the container's global modules, and tests/e2e resolves it
# through createRequire because ESM ignores NODE_PATH.
#
# These drive the real app against the real feed. They create drawings and
# delete them again afterwards; the dev stack shares one drawing store with
# whoever else is looking at it.
set -uo pipefail

FILTER=${1:-}
COMPOSE=${COMPOSE:-docker compose}

if ! $COMPOSE ps --status running --services 2>/dev/null | grep -qx playwright; then
  echo "the playwright service is not running — start it with: $COMPOSE up -d" >&2
  exit 1
fi

if [ -n "$FILTER" ]; then
  FILES=$(ls tests/e2e/*"$FILTER"*.test.mjs 2>/dev/null)
  if [ -z "$FILES" ]; then
    echo "no e2e test files match '$FILTER'" >&2
    exit 1
  fi
else
  FILES=$(ls tests/e2e/*.test.mjs)
fi

# The app is reachable as http://api:8000 from inside the compose network.
# shellcheck disable=SC2086
$COMPOSE exec -T \
  -e NODE_PATH=/usr/lib/node_modules \
  -e E2E_URL="${E2E_URL:-http://api:8000/}" \
  playwright node --test --test-concurrency=1 $(echo $FILES | sed 's#tests/e2e/#/repo/tests/e2e/#g')
