# Deployment script for production
#!/bin/bash

set -e

# Configuration
DOCKER_REGISTRY="${DOCKER_REGISTRY:-your-registry.com}"
IMAGE_NAME="${IMAGE_NAME:-homework-backend}"
TAG="${TAG:-latest}"
ENVIRONMENT="${ENVIRONMENT:-production}"

echo "🚀 Deploying Homework Backend to $ENVIRONMENT..."

# Build Docker image
echo "🏗️  Building Docker image..."
docker build -t $DOCKER_REGISTRY/$IMAGE_NAME:$TAG .

# Push to registry
echo "📤 Pushing image to registry..."
docker push $DOCKER_REGISTRY/$IMAGE_NAME:$TAG

# Deploy based on environment
case $ENVIRONMENT in
    "staging")
        echo "🎭 Deploying to staging..."
        docker-compose -f docker-compose.staging.yml down || true
        sed -i "s|image:.*|image: $DOCKER_REGISTRY/$IMAGE_NAME:$TAG|g" docker-compose.staging.yml
        docker-compose -f docker-compose.staging.yml up -d
        ;;
    "production")
        echo "🏭 Deploying to production..."
        docker-compose -f docker-compose.prod.yml down || true
        sed -i "s|image:.*|image: $DOCKER_REGISTRY/$IMAGE_NAME:$TAG|g" docker-compose.prod.yml
        docker-compose -f docker-compose.prod.yml up -d
        ;;
    *)
        echo "❌ Unknown environment: $ENVIRONMENT"
        echo "Supported environments: staging, production"
        exit 1
        ;;
esac

echo "✅ Deployment completed successfully!"
echo "🔍 Checking service health..."
sleep 10

# Health check
if curl -f http://localhost:8080/health > /dev/null 2>&1; then
    echo "💚 Service is healthy!"
else
    echo "💔 Service health check failed!"
    exit 1
fi