#!/bin/bash
# ===================================================================
# TK Factory Services - Health Check
# ===================================================================

echo "=== TK Factory Services Health Check ==="
echo ""

PASS=0
FAIL=0
SKIP=0

check_service() {
  local name="$1"
  local url="$2"
  local port="$3"

  printf "%-25s " "$name"

  # 포트 열림 확인
  if ! nc -z localhost "$port" 2>/dev/null; then
    echo "SKIP (port $port not open)"
    ((SKIP++))
    return
  fi

  # HTTP 확인
  local status
  status=$(curl -s -o /dev/null -w "%{http_code}" --connect-timeout 3 "$url" 2>/dev/null)

  if [ "$status" -ge 200 ] && [ "$status" -lt 400 ]; then
    echo "OK ($status)"
    ((PASS++))
  else
    echo "FAIL ($status)"
    ((FAIL++))
  fi
}

check_service "Gateway"             "http://localhost:30000/"              30000
check_service "SSO Auth"            "http://localhost:30050/health"        30050
check_service "System 1 API"        "http://localhost:30005/api/health"    30005
check_service "System 1 Web"        "http://localhost:30080/"              30080
check_service "System 1 FastAPI"    "http://localhost:30008/health"        30008
check_service "System 2 API"        "http://localhost:30105/api/health"    30105
check_service "System 2 Web"        "http://localhost:30180/"              30180
check_service "System 3 API"        "http://localhost:30200/api/health"    30200
check_service "System 3 Web"        "http://localhost:30280/"              30280
check_service "tkuser API"          "http://localhost:30300/api/health"    30300
check_service "tkuser Web"          "http://localhost:30380/"              30380
check_service "phpMyAdmin"          "http://localhost:30880/"              30880

echo ""
echo "=== Docker Container Status ==="
docker compose ps --format "table {{.Name}}\t{{.Status}}\t{{.Ports}}" 2>/dev/null || \
  echo "docker compose not available in this directory"

echo ""
echo "Results: PASS=$PASS  FAIL=$FAIL  SKIP=$SKIP"

if [ "$FAIL" -gt 0 ]; then
  exit 1
fi
