#!/bin/sh
set -e

echo "🚀 Starting Znakovni.hr Production Container..."

# Validate environment variables
if [ -z "$DATABASE_URL" ]; then
  echo "❌ ERROR: DATABASE_URL is required"
  exit 1
fi

if [ -z "$SESSION_SECRET" ]; then
  echo "❌ ERROR: SESSION_SECRET is required"
  exit 1
fi

# Run database migrations
cd /app/packages/backend
echo "📦 Running database migrations..."

# Try to run migrations, if database is not empty, resolve it
if ! pnpm exec prisma migrate deploy 2>&1 | tee /tmp/migrate.log; then
  # Check if error is P3005 (database not empty)
  if grep -q "P3005" /tmp/migrate.log; then
    echo "⚠️  Database already exists with data. Marking migrations as applied..."
    pnpm exec prisma migrate resolve --applied "$(ls -1 prisma/migrations | head -1)"
    echo "✅ Database baseline complete. Applying any pending migrations..."
    pnpm exec prisma migrate deploy
  else
    echo "❌ Migration failed with unexpected error"
    cat /tmp/migrate.log
    exit 1
  fi
fi

# Optional: Run seed if RUN_SEED is set to true
if [ "$RUN_SEED" = "true" ]; then
  echo "🌱 Running database seed..."
  pnpm exec prisma db seed
fi

# Optional: Regenerate GIFs if REGENERATE_GIFS is set to true
if [ "$REGENERATE_GIFS" = "true" ]; then
  echo "🎨 Regenerating GIF previews for all videos..."
  pnpm exec tsx scripts/regenerate-all-gifs.ts
fi

# Start backend server
echo "🔧 Starting backend server..."
cd /app/packages/backend
node dist/server.js &
BACKEND_PID=$!

# Wait for backend to be ready
echo "⏳ Waiting for backend to initialize..."
sleep 5

# Start nginx (reverse proxy for frontend + API)
echo "🎨 Starting nginx reverse proxy..."
nginx -g 'daemon off;' &
NGINX_PID=$!

# Trap signals for graceful shutdown
trap "echo '🛑 Shutting down...'; kill $BACKEND_PID $NGINX_PID 2>/dev/null; exit 0" SIGTERM SIGINT

echo "✅ Application started successfully!"
echo "   Application: http://0.0.0.0:5173"
echo "   - Frontend served via nginx"
echo "   - API proxied to backend at /api/*"

# Wait for processes
wait $BACKEND_PID $NGINX_PID

