#!/bin/bash
set -e

echo "🚀 Deploying Rezepte Klaus to production..."

# Check if .env.production exists
if [ ! -f .env.production ]; then
    echo "❌ Error: .env.production file not found!"
    echo "Please copy .env.production.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

echo "📥 Pulling latest changes..."
git pull origin main

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

echo "🏗️  Building and starting containers..."
docker-compose -f docker-compose.production.yml up --build -d

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

echo "🔍 Checking service health..."
HEALTHY_SERVICES=$(docker-compose -f docker-compose.production.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.production.yml ps
else
    echo "❌ Deployment failed! Check logs:"
    docker-compose -f docker-compose.production.yml logs --tail=50
    exit 1
fi

echo ""
echo "📋 Useful commands:"
echo "  View logs: docker-compose -f docker-compose.production.yml logs -f"
echo "  Stop: docker-compose -f docker-compose.production.yml down"
echo "  Restart: docker-compose -f docker-compose.production.yml restart"