#!/bin/bash
set -e

# Create log directory if it doesn't exist
mkdir -p test/e2e/logs

# Clear Nuxt cache and build output to ensure fresh build with test configuration
echo "Clearing Nuxt cache and build artifacts..."
rm -rf .nuxt .playground/.nuxt .output .playground/.output 2>/dev/null || true

# Check if we're in CI or local environment
# CI sets the CI environment variable
if [ -n "$CI" ]; then
  echo "CI environment detected - using pre-configured environment variables..."
  echo "SMTP Configuration:"
  echo "  NUXT_SMTP_HOST=$NUXT_SMTP_HOST"
  echo "  NUXT_SMTP_PORT=$NUXT_SMTP_PORT"
  echo "  NUXT_SMTP_SECURE=$NUXT_SMTP_SECURE"
  echo "  NUXT_MOCK_EMAIL=$NUXT_MOCK_EMAIL"
else
  echo "Local environment detected - using .env.test configuration..."

  # Temporarily rename .env to prevent Nuxt from loading production config
  # This ensures .env.test values are used
  if [ -f .env ]; then
    echo "Temporarily hiding .env file..."
    mv .env .env.production-backup
  fi

  # Trap to ensure .env is always restored
  restore_env() {
    if [ -f .env.production-backup ]; then
      echo "Restoring .env file..."
      mv .env.production-backup .env
    fi
  }
  trap restore_env EXIT INT TERM

  # Load .env.test and export all variables
  echo "Loading environment from .env.test..."
  set -a  # Automatically export all variables
  source .env.test
  set +a  # Disable auto-export
fi

# Start the dev server with --host to expose the port
echo "Starting dev server with test configuration..."
# In CI, don't redirect output so Playwright can capture it
# Locally, redirect to log file for cleaner test output
if [ -n "$CI" ]; then
  pnpm dev -- --host &
  DEV_PID=$!
else
  pnpm dev -- --host > test/e2e/logs/server.log 2>&1 &
  DEV_PID=$!
fi

# Wait for server to be ready by polling the URL
echo "Waiting for server to respond..."
for i in {1..60}; do
  if curl -s http://localhost:3000 > /dev/null 2>&1; then
    echo "Server is ready!"
    wait $DEV_PID
    exit 0
  fi
  sleep 2
done

echo "Server failed to start within 120 seconds"
kill $DEV_PID 2>/dev/null || true
exit 1
