#!/bin/bash
set -e

echo "🚀 Deploying Rezepte Klaus from Docker Registry..."

# Check if .env.production exists
if [ ! -f .env.production ]; then
    echo "❌ Error: .env.production file not found!"
    echo "Please copy .env.registry.example to .env.production and configure it."
    exit 1
fi

# Load environment variables
export $(cat .env.production | grep -v '^#' | xargs)

# Validate required environment variables
if [ -z "$MYSQL_PASSWORD" ] || [ -z "$CORS_ORIGIN" ]; then
    echo "❌ Error: Required environment variables not set in .env.production"
    echo "Please configure MYSQL_PASSWORD and CORS_ORIGIN"
    exit 1
fi

# Login to CitySensor registry if credentials are provided
if [ -n "$DOCKER_USERNAME" ] && [ -n "$DOCKER_PASSWORD" ] && [ -n "$DOCKER_REGISTRY" ]; then
    echo "🔐 Logging into CitySensor registry..."
    echo "$DOCKER_PASSWORD" | docker login "$DOCKER_REGISTRY" -u "$DOCKER_USERNAME" --password-stdin
fi

# Check if required SQL files exist
REQUIRED_FILES=("Rezepte.sql" "ingredients.sql" "Zubereitung.sql" "rezepte_bilder.sql")
for file in "${REQUIRED_FILES[@]}"; do
    if [ ! -f "$file" ]; then
        echo "❌ Error: Required SQL file $file not found!"
        echo "Please ensure all SQL files are present in the current directory."
        exit 1
    fi
done

echo "🛑 Stopping existing containers..."
docker-compose -f docker-compose.registry.yml down

echo "📥 Pulling latest images from registry..."
docker-compose -f docker-compose.registry.yml pull

echo "🚀 Starting containers with registry images..."
docker-compose -f docker-compose.registry.yml up -d

echo "⏳ Waiting for services to start..."
sleep 30

echo "🔍 Checking service health..."
HEALTHY_SERVICES=$(docker-compose -f docker-compose.registry.yml ps --filter "status=running" --format "table {{.Service}}\t{{.Status}}" | grep -c "Up" || true)

if [ "$HEALTHY_SERVICES" -ge 3 ]; then
    echo "✅ Deployment successful!"
    echo "🌐 Application should be available at: $CORS_ORIGIN"
    echo ""
    echo "📊 Service Status:"
    docker-compose -f docker-compose.registry.yml ps
    echo ""
    echo "🏷️  Image Information:"
    echo "Backend:  ${BACKEND_IMAGE:-ghcr.io/your-username/rezepte-klaus-backend:latest}"
    echo "Frontend: ${FRONTEND_IMAGE:-ghcr.io/your-username/rezepte-klaus-frontend:latest}"
else
    echo "❌ Deployment failed! Check logs:"
    docker-compose -f docker-compose.registry.yml logs --tail=50
    exit 1
fi

echo ""
echo "📋 Useful commands:"
echo "  View logs: docker-compose -f docker-compose.registry.yml logs -f"
echo "  Update: docker-compose -f docker-compose.registry.yml pull && docker-compose -f docker-compose.registry.yml up -d"
echo "  Stop: docker-compose -f docker-compose.registry.yml down"