#!/bin/bash
set -euo pipefail

# scripts/lab/check_all_health.sh

GREEN='\033[0;32m'
RED='\033[0;31m'
NC='\033[0m'

echo -e "${GREEN}🏥 Checking Services Health...${NC}"

# Function to check url
check_url() {
    local name=$1
    local url=$2
    local required=$3 # 1 for required, 0 for optional
    
    if curl -fsS "$url" > /dev/null 2>&1; then
        echo -e "- $name : ${GREEN}OK${NC}"
        return 0
    else
        echo -e "- $name : ${RED}KO${NC}"
        if [ "$required" -eq 1 ]; then
            return 1
        else
            return 0
        fi
    fi
}

FAILED=0

echo "[SERVICES]"

# Backend API
check_url "veza-backend-api (health)" "http://localhost:8080/api/v1/health" 1 || FAILED=1
check_url "veza-backend-api (readyz)" "http://localhost:8080/api/v1/readyz" 1 || FAILED=1

# Chat Server
check_url "veza-chat-server (health)" "http://localhost:8081/health" 1 || FAILED=1
# readyz might not exist on all, but requested to check
check_url "veza-chat-server (readyz)" "http://localhost:8081/readyz" 0 || true

# Stream Server
check_url "veza-stream-server (healthz)" "http://localhost:8082/healthz" 1 || FAILED=1

# Frontend
check_url "apps/web (page)" "http://localhost:3000" 1 || FAILED=1


if [ $FAILED -ne 0 ]; then
    echo -e "\n${RED}❌ Some critical services are KO${NC}"
    exit 1
else
    echo -e "\n${GREEN}✅ All critical services are UP${NC}"
    exit 0
fi
