#!/bin/sh
set -e

echo "🚀 Starting Mawidi application..."
echo "📦 Version: v4.0 (Mar 2026 - Convex-Only Database)"
echo ""

# Validate critical environment variables
echo "🔍 Validating environment variables..."

MISSING_VARS=""
if [ -z "$NEXTAUTH_SECRET" ]; then MISSING_VARS="$MISSING_VARS NEXTAUTH_SECRET"; fi
if [ -z "$NEXTAUTH_URL" ]; then MISSING_VARS="$MISSING_VARS NEXTAUTH_URL"; fi

if [ -n "$MISSING_VARS" ]; then
  echo "❌ ERROR: Missing required environment variables:$MISSING_VARS"
  echo "Please set these variables in your .env file or docker-compose.yml"
  exit 1
fi

# Warn about optional but recommended variables
if [ -z "$STRIPE_SECRET_KEY" ]; then
  echo "⚠️  WARNING: STRIPE_SECRET_KEY not set - payment features will not work"
fi

echo "✅ Environment validation passed"
echo ""

# Check if running in production or development
if [ "$NODE_ENV" = "production" ]; then
  echo "🏭 Production mode detected"

  # Optional: Seed blog posts if SEED_BLOG_ON_START is true
  if [ "$SEED_BLOG_ON_START" = "true" ]; then
    echo "📝 Seeding blog posts from MDX files..."
    npx tsx scripts/migrate-blog-posts.ts || echo "⚠️  Blog seeding failed"
  fi

  # Optional: Seed demo bookings for testing
  if [ "$SEED_DEMO_BOOKINGS" = "true" ]; then
    echo "🎯 Seeding demo bookings..."
    npx tsx scripts/seed-demo-bookings.ts || echo "⚠️  Demo seeding failed"
  fi
else
  echo "🔧 Development mode detected"
fi

echo ""
echo "✅ Initialization complete"
echo "🌐 Starting Next.js server on port ${PORT:-9000}..."
echo "📍 Health check endpoint: http://localhost:${PORT:-9000}/api/health"
echo "🗄️  Database: Convex (primary)"
echo ""

# Start the application
exec node server.js
