#!/usr/bin/env bash
set -euo pipefail

# Full e2e workflow: start Docker Chrome, run Playwright tests, stop container.
#
# Usage: ./bin/e2e-full.sh [extra playwright args...]
#
# Requires:
#   - Docker (colima or Docker Desktop running)
#   - Phoenix dev server running (default http://localhost:8056)

SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"
PROJECT_DIR="$(cd "$SCRIPT_DIR/.." && pwd)"

cd "$PROJECT_DIR"

echo "=== Starting Chrome container ==="
docker compose -f docker-compose.chrome.yml up -d

echo "=== Waiting for Chrome to be ready... ==="
for i in $(seq 1 30); do
  if curl -s -o /dev/null -w "%{http_code}" http://localhost:3000/ 2>/dev/null | grep -q 200; then
    echo "Chrome is ready!"
    break
  fi
  if [ "$i" -eq 30 ]; then
    echo "Timed out waiting for Chrome."
    docker compose -f docker-compose.chrome.yml logs --tail=20
    exit 1
  fi
  sleep 1
done

echo "=== Running Playwright e2e tests against Docker Chrome ==="
cd assets && PLAYWRIGHT_BROWSERS_PATH=node_modules/playwright-core/.local-browsers \
  npx playwright test --config=../playwright.docker.config.ts "$@"

EXIT_CODE=$?

cd "$PROJECT_DIR"
echo "=== Stopping Chrome container ==="
docker compose -f docker-compose.chrome.yml down

exit $EXIT_CODE