#!/bin/bash
# Health check script for Overseas Appointment System
# Can be used with monitoring tools like Nagios, Zabbix, etc.

set -e

API_URL="${API_URL:-http://localhost:3000}"
TIMEOUT=10

echo "Checking system health..."

# Check API health
echo -n "API Health: "
API_RESPONSE=$(curl -s -o /dev/null -w "%{http_code}" --max-time ${TIMEOUT} "${API_URL}/health" 2>/dev/null || echo "000")
if [ "$API_RESPONSE" = "200" ]; then
    echo "OK"
else
    echo "FAILED (HTTP ${API_RESPONSE})"
    exit 1
fi

# Check MySQL (via Docker)
echo -n "MySQL: "
if docker exec overseas-appointment-mysql mysqladmin ping -h localhost -u root -p"${MYSQL_ROOT_PASSWORD:-root_password}" --silent 2>/dev/null; then
    echo "OK"
else
    echo "FAILED"
    exit 1
fi

# Check Redis (via Docker)
echo -n "Redis: "
if docker exec overseas-appointment-redis redis-cli ping 2>/dev/null | grep -q "PONG"; then
    echo "OK"
else
    echo "FAILED"
    exit 1
fi

# Check Nginx (via Docker)
echo -n "Nginx: "
if docker exec overseas-appointment-nginx nginx -t 2>/dev/null; then
    echo "OK"
else
    echo "FAILED"
    exit 1
fi

echo ""
echo "All services are healthy!"
exit 0
