#!/bin/bash

# Scale services in Kubernetes
# Usage: ./scale.sh [environment] [service] [replicas]

set -e

ENVIRONMENT=${1:-prod}
SERVICE=${2}
REPLICAS=${3}
NAMESPACE="portfolio-${ENVIRONMENT}"

if [[ -z "${SERVICE}" || -z "${REPLICAS}" ]]; then
    echo "Usage: ./scale.sh [environment] [service] [replicas]"
    echo ""
    echo "Available services:"
    echo "  - user-service"
    echo "  - task-service"
    echo "  - analytics-service"
    echo "  - diagram-service"
    echo "  - api-gateway"
    echo "  - frontend"
    echo "  - all (scales all services to specified replicas)"
    echo ""
    echo "Example: ./scale.sh prod api-gateway 5"
    exit 1
fi

# Validate replicas is a number
if ! [[ "${REPLICAS}" =~ ^[0-9]+$ ]]; then
    echo "❌ Replicas must be a positive number"
    exit 1
fi

echo "📈 Scaling ${SERVICE} to ${REPLICAS} replicas in ${ENVIRONMENT} environment..."

if [[ "${SERVICE}" == "all" ]]; then
    echo "📈 Scaling all services to ${REPLICAS} replicas..."
    kubectl scale deployment user-service --replicas=${REPLICAS} -n ${NAMESPACE}
    kubectl scale deployment task-service --replicas=${REPLICAS} -n ${NAMESPACE}
    kubectl scale deployment analytics-service --replicas=${REPLICAS} -n ${NAMESPACE}
    kubectl scale deployment diagram-service --replicas=${REPLICAS} -n ${NAMESPACE}
    kubectl scale deployment api-gateway --replicas=${REPLICAS} -n ${NAMESPACE}
    kubectl scale deployment frontend --replicas=${REPLICAS} -n ${NAMESPACE}
else
    kubectl scale deployment ${SERVICE} --replicas=${REPLICAS} -n ${NAMESPACE}
fi

echo "✅ Scaling completed!"
echo ""
echo "📋 Current status:"
kubectl get pods -n ${NAMESPACE} -l app=${SERVICE}