#!/bin/bash

# Health check script for Mawidi services
# Usage: ./scripts/health-check.sh [service]

set -e

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

check_service() {
    local name=$1
    local url=$2

    echo -n "Checking $name... "

    if curl -f -s "$url" > /dev/null; then
        echo -e "${GREEN}✓ Healthy${NC}"
        return 0
    else
        echo -e "${RED}✗ Unhealthy${NC}"
        return 1
    fi
}

echo "====================================="
echo "    Mawidi Services Health Check     "
echo "====================================="
echo ""

# Check which services to test
SERVICE=${1:-all}

case $SERVICE in
    prod|production)
        check_service "Production App" "http://localhost:9000/api/health"
        ;;
    dev|development)
        check_service "Development App" "http://localhost:3000/api/health"
        ;;
    redis)
        echo -n "Checking Redis... "
        if docker exec mawidi-redis redis-cli ping > /dev/null 2>&1; then
            echo -e "${GREEN}✓ PONG${NC}"
        else
            echo -e "${RED}✗ No response${NC}"
        fi
        ;;
    nginx)
        check_service "Nginx Proxy" "http://localhost/health"
        ;;
    all|*)
        check_service "Production App" "http://localhost:9000/api/health" || true
        check_service "Development App" "http://localhost:3000/api/health" || true

        echo -n "Checking Redis... "
        if docker exec mawidi-redis redis-cli ping > /dev/null 2>&1; then
            echo -e "${GREEN}✓ PONG${NC}"
        else
            echo -e "${YELLOW}○ Not running${NC}"
        fi

        check_service "Nginx Proxy" "http://localhost/health" || true
        ;;
esac

echo ""
echo "====================================="

# Check Docker containers
echo ""
echo "Docker Container Status:"
docker ps --format "table {{.Names}}\t{{.Status}}\t{{.Ports}}" | grep mawidi || echo "No Mawidi containers running"