#!/bin/sh
set -e

# Export version if available
if [ -f /app/version.txt ]; then
    export APP_VERSION=$(cat /app/version.txt)
    echo "App version: $APP_VERSION"
fi

echo "Starting deployment..."

# Run migrations with fallback to baseline if needed
echo "Running database migrations..."
if ! npx prisma migrate deploy; then
    echo "⚠️  Migration failed, attempting to baseline existing database..."
    if [ -f /app/scripts/baseline-migrations.sh ]; then
        sh /app/scripts/baseline-migrations.sh
        echo "Retrying migrations after baseline..."
        npx prisma migrate deploy || {
            echo "❌ Migration failed even after baseline. Please check your database."
            exit 1
        }
    else
        echo "❌ ERROR: Migration failed and baseline script not found at /app/scripts/baseline-migrations.sh"
        exit 1
    fi
fi
echo "✅ Migrations completed successfully"

# Start the application
echo "Starting application..."
exec node server.js
