#!/bin/bash

# Dashboard WebSocket Integration Test Runner
# Usage: ./run_dashboard_test.sh [--db path/to/database.db]

set -e

# Default values
DB_PATH=""
FLUTTER_TEST_ARGS=""

# Parse command line arguments
while [[ $# -gt 0 ]]; do
  case $1 in
    --db)
      DB_PATH="$2"
      FLUTTER_TEST_ARGS="--db $2"
      shift 2
      ;;
    -h|--help)
      echo "Usage: $0 [--db path/to/database.db]"
      echo ""
      echo "Options:"
      echo "  --db PATH    Use custom database file instead of default database"
      echo "  -h, --help   Show this help message"
      echo ""
      echo "Examples:"
      echo "  $0                           # Run with default database"
      echo "  $0 --db test_data.db         # Run with custom database file"
      echo "  $0 --db ../xp_server/test/high_achiever.db    # Run with golden test database"
      echo ""
      echo "Golden test databases (create with xp_server/test/create_golden_db.dart):"
      echo "  high_achiever.db     - User with many achievements and high level"
      echo "  new_user.db          - Fresh user with minimal data"
      echo "  level_up_ready.db    - User close to leveling up"
      echo "  achievement_rich.db  - User with many recent achievements"
      echo "  focus_master.db      - User with many focus sessions"
      exit 0
      ;;
    *)
      echo "Unknown option: $1"
      echo "Use --help for usage information"
      exit 1
      ;;
  esac
done

# Change to dashboard directory
cd "$(dirname "$0")/../.."

echo "🚀 Running Dashboard WebSocket Integration Tests"
echo "================================================"

if [[ -n "$DB_PATH" ]]; then
  echo "🗄️  Using custom database: $DB_PATH"
  
  # Check if database file exists
  if [[ ! -f "$DB_PATH" ]]; then
    echo "❌ Error: Database file '$DB_PATH' not found"
    echo ""
    echo "💡 To create golden test databases:"
    echo "   cd ../xp_server/test"
    echo "   dart create_golden_db.dart high_achiever high_achiever.db"
    echo "   dart create_golden_db.dart new_user new_user.db"
    echo "   # etc..."
    exit 1
  fi
else
  echo "🗄️  Using server's default database"
fi

echo ""

# Set environment variable for test arguments
export FLUTTER_TEST_ARGS="$FLUTTER_TEST_ARGS"

# Run the integration test
echo "🧪 Executing tests..."
flutter test test/integration/dashboard_websocket_integration_test.dart --verbose

echo ""
echo "✅ Tests completed successfully!"

if [[ -n "$DB_PATH" ]]; then
  echo "📊 Custom database '$DB_PATH' was used for testing"
fi

echo ""
echo "💡 Tips:"
echo "   - Create golden test databases with: cd ../xp_server/test && dart create_golden_db.dart <scenario>"
echo "   - Available scenarios: high_achiever, new_user, level_up_ready, achievement_rich, focus_master"
echo "   - Test with different scenarios to verify WebSocket behavior under various conditions"
