#!/usr/bin/env bash
# ===============================================================================================================
# health-check.sh - Verifica que la API backend esté saludable
# Descripción:
#       Realiza peticiones al endpoint de salud de la API con reintentos.
#       Puede ejecutarse desde la EC2 localmente o desde el pipeline.
#
# Uso:
#       HEALTH_URL=http://localhost:8080/actuator/health bash health-check.sh
#
# Autor: Área de Tecnología y Desarrollo - CCsoft
# ===============================================================================================================

set -euo pipefail

# -------------------------------------------------------------------------------
# Configuración
# -------------------------------------------------------------------------------
HEALTH_URL="${HEALTH_URL:-http://localhost:8080/actuator/health}"
MAX_RETRIES="${MAX_RETRIES:-30}"
RETRY_INTERVAL="${RETRY_INTERVAL:-2}"

readonly CLR_RED='\033[0;31m'
readonly CLR_GREEN='\033[0;32m'
readonly CLR_YELLOW='\033[1;33m'
readonly CLR_BLUE='\033[0;34m'
readonly CLR_NC='\033[0m'

_log_info()  { echo -e "${CLR_GREEN}[INFO]${CLR_NC} $*"; }
_log_warn()  { echo -e "${CLR_YELLOW}[WARN]${CLR_NC} $*" >&2; }
_log_error() { echo -e "${CLR_RED}[ERROR]${CLR_NC} $*" >&2; }
_log_step()  { echo ""; echo -e "${CLR_BLUE}==== $* ====${CLR_NC}"; }

# -------------------------------------------------------------------------------
# Health Check
# -------------------------------------------------------------------------------
main() {
    _log_step "Health Check: ${HEALTH_URL}"

    local attempt=1
    while [[ $attempt -le $MAX_RETRIES ]]; do
        _log_info "Intento ${attempt}/${MAX_RETRIES}..."

        if curl -sf "${HEALTH_URL}" | grep -q '"status":"UP"'; then
            _log_info "Health check PASÓ - API saludable"
            return 0
        fi

        if [[ $attempt -lt $MAX_RETRIES ]]; then
            _log_warn "API no responde aún, reintentando en ${RETRY_INTERVAL}s..."
            sleep "${RETRY_INTERVAL}"
        fi

        ((attempt++))
    done

    _log_error "Health check FALLÓ después de ${MAX_RETRIES} intentos"
    return 1
}

main "$@"
