#!/bin/bash
set -euo pipefail

# scripts/lab/check_infra.sh

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

VEZA_LAB_DSN="${VEZA_LAB_DSN:-postgres://veza:veza_password@localhost:5432/veza_lab?sslmode=disable}"

echo -e "${GREEN}🔍 Checking Infrastructure Health...${NC}"

# Check Postgres
if command -v psql &> /dev/null; then
    if psql "$VEZA_LAB_DSN" -c "SELECT 1" > /dev/null 2>&1; then
        echo -e "PostgreSQL : ${GREEN}OK${NC}"
    else
        echo -e "PostgreSQL : ${RED}KO${NC}"
        exit 1
    fi
elif command -v pg_isready &> /dev/null; then
    # Fallback to pg_isready if psql not installed, extracting logic from DSN
    # Assuming standard localhost/port from DSN default
    if pg_isready -h localhost -p 5432 -U veza -d veza_lab > /dev/null 2>&1; then
        echo -e "PostgreSQL : ${GREEN}OK${NC}"
    else
         echo -e "PostgreSQL : ${RED}KO${NC}"
         exit 1
    fi
else
    # Fallback to docker exec if neither tool is on host
    if docker exec veza-lab-postgres pg_isready -U veza -d veza_lab > /dev/null 2>&1; then
        echo -e "PostgreSQL : ${GREEN}OK${NC} (via docker exec)"
    else
        echo -e "PostgreSQL : ${RED}KO${NC}"
        exit 1
    fi
fi

# Check Redis
if docker exec veza-lab-redis redis-cli ping | grep -q "PONG"; then
    echo -e "Redis      : ${GREEN}OK${NC}"
else
    echo -e "Redis      : ${RED}KO${NC}"
fi

# Check RabbitMQ
if docker exec veza-lab-rabbitmq rabbitmq-diagnostics -q ping > /dev/null 2>&1; then
    echo -e "RabbitMQ   : ${GREEN}OK${NC}"
else
     echo -e "RabbitMQ   : ${RED}KO${NC}"
fi

# Check HAProxy
if docker exec veza-lab-haproxy haproxy -c -f /usr/local/etc/haproxy/haproxy.cfg > /dev/null 2>&1; then
    echo -e "HAProxy    : ${GREEN}OK${NC}"
else
    echo -e "HAProxy    : ${RED}KO${NC}"
fi
