#!/bin/bash

# Docker production deployment script for Mawidi site
# Builds and deploys both production and preview instances

echo "🚀 Starting Docker production deployment..."

# Change to project root
cd "$(dirname "$0")/.." || exit 1

# Check if docker-compose is available
if ! command -v docker-compose &> /dev/null; then
    echo "Using docker compose (v2) instead of docker-compose..."
    COMPOSE_CMD="docker compose"
else
    COMPOSE_CMD="docker-compose"
fi

# Parse command line arguments
SERVICES="mawidi-app"
if [ "$1" == "--all" ]; then
    SERVICES="mawidi-app mawidi-app-preview"
    echo "📌 Deploying both production and preview instances"
elif [ "$1" == "--preview" ]; then
    SERVICES="mawidi-app-preview"
    echo "📌 Deploying preview instance only"
else
    echo "📌 Deploying production instance only"
fi

# Build services
echo "📦 Building Docker images..."
for service in $SERVICES; do
    echo "Building $service..."
    $COMPOSE_CMD build --no-cache $service
    if [ $? -ne 0 ]; then
        echo "❌ Failed to build $service"
        exit 1
    fi
done

echo "✅ All images built successfully"

# Stop existing containers
echo "🛑 Stopping existing containers..."
$COMPOSE_CMD stop $SERVICES
$COMPOSE_CMD rm -f $SERVICES

# Start services
echo "🚀 Starting production containers..."
$COMPOSE_CMD up -d $SERVICES

if [ $? -eq 0 ]; then
    echo "✅ Containers started successfully!"

    # Display service URLs
    echo ""
    echo "🌐 Services available at:"
    if [[ $SERVICES == *"mawidi-app"* ]] && [[ $SERVICES != *"preview"* ]] || [[ $SERVICES == *"mawidi-app "* ]]; then
        echo "   Production: http://localhost:9000"
    fi
    if [[ $SERVICES == *"preview"* ]]; then
        echo "   Preview: http://localhost:9150"
    fi

    # Wait for containers to be ready
    echo ""
    echo "⏳ Waiting for containers to be ready..."
    sleep 8

    # Check container health
    echo "🔍 Checking container health..."
    for service in $SERVICES; do
        if $COMPOSE_CMD ps | grep -q "$service.*Up.*healthy"; then
            echo "✅ $service is running and healthy"
        elif $COMPOSE_CMD ps | grep -q "$service.*Up"; then
            echo "⚠️ $service is running (health check pending)"
        else
            echo "❌ $service failed to start properly"
            $COMPOSE_CMD logs --tail=20 $service
            exit 1
        fi
    done

    echo ""
    echo "🎉 Production deployment complete!"
    echo ""
    echo "📋 View logs with:"
    echo "   docker-compose logs -f $SERVICES"
else
    echo "❌ Failed to start containers"
    exit 1
fi