#!/bin/bash
# EN: Check health of all running services
# VI: Kiểm tra health của tất cả services đang chạy

set -e

# Colors
GREEN='\033[0;32m'
RED='\033[0;31m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
NC='\033[0m' # No Color

echo -e "${BLUE}━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━${NC}"
echo -e "${BLUE}  Service Health Check${NC}"
echo -e "${BLUE}━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━${NC}"
echo ""

# Default base URL
BASE_URL="${BASE_URL:-http://localhost}"
TIMEOUT=5

check_health() {
    local service=$1
    local path=$2
    local url="${BASE_URL}${path}"
    
    echo -n "Checking $service... "
    
    if response=$(curl -s -o /dev/null -w "%{http_code}" --max-time $TIMEOUT "$url" 2>/dev/null); then
        if [ "$response" = "200" ]; then
            echo -e "${GREEN}✓ Healthy (200)${NC}"
            return 0
        else
            echo -e "${YELLOW}⚠ Response: $response${NC}"
            return 1
        fi
    else
        echo -e "${RED}✗ Not reachable${NC}"
        return 1
    fi
}

# Track results
TOTAL=0
HEALTHY=0
UNHEALTHY=0

# Service list (customize based on your services)
SERVICES=(
    "IAM Service:/api/v1/iam/health"
    "Storage Service:/api/v1/storage/health"
    "Catalog Service:/api/v1/catalog/health"
    "Order Service:/api/v1/order/health"
    "Inventory Service:/api/v1/inventory/health"
    "F&B Engine:/api/v1/fnb-engine/health"
    "Booking Service:/api/v1/booking/health"
)

for SERVICE_INFO in "${SERVICES[@]}"; do
    IFS=':' read -r NAME PATH <<< "$SERVICE_INFO"
    ((TOTAL++))
    
    if check_health "$NAME" "$PATH"; then
        ((HEALTHY++))
    else
        ((UNHEALTHY++))
    fi
done

echo ""
echo -e "${BLUE}━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━${NC}"
echo "Summary:"
echo "  Total services: $TOTAL"
echo -e "  Healthy: ${GREEN}$HEALTHY${NC}"
echo -e "  Unhealthy: ${RED}$UNHEALTHY${NC}"
echo ""

if [ $UNHEALTHY -eq 0 ]; then
    echo -e "${GREEN}✓ All services are healthy!${NC}"
    exit 0
else
    echo -e "${YELLOW}⚠ Some services are not healthy${NC}"
    echo ""
    echo "Troubleshooting:"
    echo "  • Check if services are running: docker-compose ps"
    echo "  • View logs: docker-compose logs -f <service-name>"
    echo "  • Restart service: docker-compose restart <service-name>"
    exit 1
fi
