#!/bin/bash
# Test dashboard CRUD operations - with timeout protection

set -e

echo "🧪 Testing Dashboard CRUD operations..."
echo ""

# Function to run test with timeout
run_with_timeout() {
  local timeout=$1
  local cmd=$2
  
  # Run command in background
  eval "$cmd" &
  local pid=$!
  
  # Wait with timeout
  local count=0
  while kill -0 $pid 2>/dev/null; do
    if [ $count -ge $timeout ]; then
      echo "⏱️  Timeout reached (${timeout}s), killing process..."
      kill -9 $pid 2>/dev/null || true
      return 124
    fi
    sleep 1
    ((count++))
  done
  
  # Get exit code
  wait $pid
  return $?
}

# Check if server is running
if ! curl -s http://localhost:5173/ > /dev/null 2>&1; then
  echo "⚠️  Dev server not running on http://localhost:5173"
  echo "   Starting server in e2e mode..."
  pnpm --filter @my-roadtrip/web dev -- --mode e2e > /tmp/vite-e2e.log 2>&1 &
  SERVER_PID=$!
  echo "   Waiting for server to be ready..."
  
  # Wait up to 30s for server
  for i in {1..30}; do
    if curl -s http://localhost:5173/ > /dev/null 2>&1; then
      echo "✅ Server ready!"
      break
    fi
    sleep 1
  done
fi

echo "🎯 Running dashboard CRUD test (60s timeout)..."
echo ""

# Run test with 60s timeout
if run_with_timeout 60 "pnpm exec playwright test dashboard-crud.spec.ts --project=chromium --workers=1 2>&1"; then
  echo ""
  echo "✅ Tests PASSED!"
  exit 0
else
  EXIT_CODE=$?
  echo ""
  if [ $EXIT_CODE -eq 124 ]; then
    echo "❌ Tests TIMED OUT after 60s"
  else
    echo "❌ Tests FAILED (exit code: $EXIT_CODE)"
  fi
  
  # Show last few lines of output
  echo ""
  echo "Last test output:"
  tail -20 /tmp/playwright-test.log 2>/dev/null || echo "(no log available)"
  
  exit $EXIT_CODE
fi
