#!/usr/bin/env bash
# =============================================================================
# scripts/e2e-ci.sh — Run E2E tests against docker-compose.ci.yml services
#
# This script orchestrates the full CI-like E2E test flow locally:
#   1. Starts CI containers (postgres, redis, typesense, minio)
#   2. Waits for all healthchecks to pass
#   3. Runs Prisma generate + migrate + seed
#   4. Executes the Playwright E2E suite
#   5. Tears down containers
#
# Usage:
#   ./scripts/e2e-ci.sh          # run all E2E tests
#   ./scripts/e2e-ci.sh --api    # run only API tests
#   ./scripts/e2e-ci.sh --web    # run only Web tests
#   ./scripts/e2e-ci.sh --keep   # keep containers running after tests
# =============================================================================
set -euo pipefail

ROOT_DIR="$(cd "$(dirname "$0")/.." && pwd)"
COMPOSE_FILE="$ROOT_DIR/docker-compose.ci.yml"
ENV_CI_FILE="$ROOT_DIR/.env.ci"
ENV_TEST_FILE="$ROOT_DIR/.env.test"
COMPOSE_CMD="docker compose --env-file $ENV_CI_FILE -f $COMPOSE_FILE"
KEEP_CONTAINERS=false
PROJECT_FLAG=""

# Parse arguments
for arg in "$@"; do
  case "$arg" in
    --api) PROJECT_FLAG="--project=api" ;;
    --web) PROJECT_FLAG="--project=web" ;;
    --keep) KEEP_CONTAINERS=true ;;
    --help|-h)
      echo "Usage: $0 [--api|--web] [--keep]"
      echo "  --api   Run only API E2E tests"
      echo "  --web   Run only Web E2E tests"
      echo "  --keep  Keep CI containers running after tests"
      exit 0
      ;;
  esac
done

# Colors
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
CYAN='\033[0;36m'
NC='\033[0m'

info() { echo -e "${CYAN}[e2e-ci]${NC} $*"; }
success() { echo -e "${GREEN}[e2e-ci]${NC} $*"; }
warn() { echo -e "${YELLOW}[e2e-ci]${NC} $*"; }
error() { echo -e "${RED}[e2e-ci]${NC} $*"; }

cleanup() {
  if [ "$KEEP_CONTAINERS" = true ]; then
    warn "Keeping CI containers running (use '$COMPOSE_CMD down -v' to stop)"
  else
    info "Stopping CI containers..."
    $COMPOSE_CMD down -v --remove-orphans 2>/dev/null || true
  fi
}

# Always clean up on exit (unless --keep)
trap cleanup EXIT

cd "$ROOT_DIR"

# Step 1: Load test env vars
info "Loading test environment from $ENV_TEST_FILE..."
if [ ! -f "$ENV_TEST_FILE" ]; then
  error ".env.test not found. Please create it first."
  exit 1
fi
set -a
# shellcheck source=/dev/null
source "$ENV_TEST_FILE"
set +a

# Step 2: Start CI containers
info "Starting CI containers..."
$COMPOSE_CMD down -v --remove-orphans 2>/dev/null || true
$COMPOSE_CMD up -d --wait

# Verify services are healthy
info "Verifying service health..."
SERVICES=("goodgo-ci-postgres" "goodgo-ci-redis" "goodgo-ci-typesense" "goodgo-ci-minio")
for svc in "${SERVICES[@]}"; do
  STATUS=$(docker inspect --format='{{.State.Health.Status}}' "$svc" 2>/dev/null || echo "missing")
  if [ "$STATUS" = "healthy" ]; then
    success "  ✓ $svc is healthy"
  else
    error "  ✗ $svc status: $STATUS"
    docker logs "$svc" --tail 20 2>/dev/null
    exit 1
  fi
done

# Step 3: Generate Prisma client
info "Generating Prisma client..."
pnpm db:generate

# Step 4: Run migrations
info "Running database migrations..."
pnpm db:migrate:deploy

# Step 5: Seed database
info "Seeding test database..."
pnpm db:seed

success "Database ready."

# Step 6: Run E2E tests
info "Running Playwright E2E tests..."
# Set CI=true so Playwright config uses CI settings (retries, single worker, etc.)
# but globalSetup skips migrations since we already ran them above.
CI=true pnpm test:e2e $PROJECT_FLAG
TEST_EXIT=$?

if [ $TEST_EXIT -eq 0 ]; then
  success "All E2E tests passed! ✓"
else
  error "Some E2E tests failed (exit code: $TEST_EXIT)"
fi

exit $TEST_EXIT
