#!/bin/sh

set -e

echo "🚀 [Docker Start] Starting Drizzle Switcher..."

echo "📋 [Docker Start] Checking environment configuration..."
echo "   NODE_ENV: ${NODE_ENV:-not set}"
echo "   APP_ENV: ${APP_ENV:-not set}"

# 2. Ensure the database directory exists
echo "📁 [Docker Start] Creating database directory..."
mkdir -p /app/db
ls -la /app/db

# 3. Run database initialization
echo "🗄️  [Docker Start] Initializing database..."

# Method 1: Use Node.js initialization script (recommended)
if [ -f "./scripts/init-db.js" ]; then
    echo "   Using Node.js initialization script..."
    node ./scripts/init-db.js
    echo "   Node.js initialization script finished."
fi

# Method 2: Fallback - Use drizzle-kit to migrate directly
if [ -f "./drizzle.config.app.ts" ]; then
    echo "   Fallback: Running drizzle-kit migration..."
    npx drizzle-kit migrate --config=./drizzle.config.app.ts || echo "   ⚠️  drizzle-kit migration failed, will rely on runtime initialization"
fi

# Check if the database file was created
if [ -f "/app/db/config.db" ]; then
    echo "   ✅ Database file created: /app/db/config.db"
    ls -la /app/db/
else
    echo "   ⚠️  Database file not created, the application will initialize it at runtime"
fi

# 4. Optional: Initialize data from configuration file
if [ -f "./db-config.json" ]; then
    echo "📝 [Docker Start] Found configuration file db-config.json"
    # Note: Actual data import needs to be done via API after the application starts
else
    echo "📝 [Docker Start] db-config.json not found, using default configuration"
fi

# 5. Start Next.js application
echo "🌐 [Docker Start] Starting Next.js application..."
echo "   Application will start at http://localhost:3000"
echo "   Health check endpoint: http://localhost:3000/api/health"

# Use exec to replace the current process to ensure signals are passed correctly
exec node_modules/.bin/next start