#!/usr/bin/env bash
# ============================================================================
# ChatApp - Health Check Script
# Verifies that all services are up and running
# Usage: ./scripts/health-check.sh
# ============================================================================
set -euo pipefail

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

# Service definitions: name -> check command
check_service() {
  local name="$1"
  local check_cmd="$2"
  local description="$3"

  if eval "${check_cmd}" > /dev/null 2>&1; then
    echo -e "  ${GREEN}✓${NC} ${name} - ${description}"
    return 0
  else
    echo -e "  ${RED}✗${NC} ${name} - ${description}"
    return 1
  fi
}

echo -e "${YELLOW}=== ChatApp Health Check ===${NC}"
echo ""

ALL_HEALTHY=true

# --- Infrastructure Services ---
echo -e "${YELLOW}[Infrastructure]${NC}"

check_service \
  "PostgreSQL" \
  "docker exec chatapp-postgres pg_isready -U chatapp 2>/dev/null" \
  "Database is accepting connections" || ALL_HEALTHY=false

check_service \
  "Redis" \
  "docker exec chatapp-redis redis-cli ping 2>/dev/null | grep -q PONG" \
  "Cache and pub/sub ready" || ALL_HEALTHY=false

check_service \
  "MinIO" \
  "curl -sf http://localhost:9000/minio/health/live 2>/dev/null" \
  "S3-compatible storage ready" || ALL_HEALTHY=false

check_service \
  "Meilisearch" \
  "curl -sf http://localhost:7700/health 2>/dev/null" \
  "Full-text search engine ready" || ALL_HEALTHY=false

echo ""

# --- Application Services ---
echo -e "${YELLOW}[Application]${NC}"

check_service \
  "API" \
  "curl -sf http://localhost:3010/api/v1/health 2>/dev/null" \
  "REST API on port 3010" || ALL_HEALTHY=false

check_service \
  "Realtime" \
  "curl -sf http://localhost:3002/health 2>/dev/null" \
  "WebSocket gateway on port 3002" || ALL_HEALTHY=false

check_service \
  "Frontend" \
  "curl -sf http://localhost:3001 2>/dev/null" \
  "Next.js frontend on port 3001" || ALL_HEALTHY=false

check_service \
  "Workers" \
  "docker ps --format '{{.Names}}' | grep -q chatapp-workers" \
  "Background workers running" || ALL_HEALTHY=false

echo ""

# --- Summary ---
if [ "${ALL_HEALTHY}" = true ]; then
  echo -e "${GREEN}=== All services healthy ===${NC}"
  exit 0
else
  echo -e "${RED}=== Some services are unhealthy ===${NC}"
  exit 1
fi