#!/bin/bash

# Fonction pour afficher les messages colorés
log_success() {
  echo -e "\e[32m✔ SUCCESS: $1\e[0m"
}

log_failure() {
  echo -e "\e[31m✖ FAILURE: $1\e[0m"
  EXIT_CODE=1
}

EXIT_CODE=0

echo "Executing infrastructure validation script..."
echo "Waiting for services to be ready (approx. 30 seconds)..."
sleep 30 # Give services some time to start up

# Test 1: Frontend (HTML)
echo "Testing Frontend (https://localhost/)..."
RESPONSE=$(curl -k -s -o /dev/null -w "%{http_code}" https://localhost/)
if [ "$RESPONSE" -eq 200 ]; then
  log_success "Frontend is reachable (HTTP 200)."
else
  log_failure "Frontend check failed (HTTP $RESPONSE)."
fi

# Test 2: Go API (Health endpoint)
echo "Testing Go API (https://localhost/api/v1/health)..."
# Expecting 200 OK or 401 Unauthorized if auth is enabled, both indicate API is hit.
RESPONSE=$(curl -k -s -o /dev/null -w "%{http_code}" https://localhost/api/v1/health)
if [ "$RESPONSE" -eq 200 ] || [ "$RESPONSE" -eq 401 ]; then
  log_success "Go API is reachable (HTTP $RESPONSE)."
else
  log_failure "Go API check failed (HTTP $RESPONSE)."
fi

# Test 3: Rust Chat (WebSocket, expecting 400 or 'Upgrade Required')
echo "Testing Rust Chat (https://localhost/ws/chat)..."
# For WebSockets, a non-101 response (like 400 Bad Request or 426 Upgrade Required)
# indicates HAProxy successfully routed to the WebSocket server.
HEADERS=$(curl -k -s -i https://localhost/ws/chat)
if echo "$HEADERS" | grep -q "HTTP/1.1 400 Bad Request" || echo "$HEADERS" | grep -q "HTTP/1.1 426 Upgrade Required"; then
  log_success "Rust Chat service is reachable (HAProxy routed WebSocket)."
else
  log_failure "Rust Chat check failed. Response headers: \n$HEADERS"
fi

# Test 4: Rust Stream (HLS endpoint, expecting server response, not 503)
echo "Testing Rust Stream (https://localhost/hls/test)..."
# Expecting a response from the stream server (e.g., 404 Not Found for non-existent stream)
# A 503 Service Unavailable would indicate HAProxy failed to route.
RESPONSE=$(curl -k -s -o /dev/null -w "%{http_code}" https://localhost/hls/test)
if [ "$RESPONSE" -ne 503 ]; then # Any response other than 503 from HAProxy is good.
  log_success "Rust Stream service is reachable (HTTP $RESPONSE, not 503)."
else
  log_failure "Rust Stream check failed (HTTP $RESPONSE, potentially HAProxy issue)."
fi

if [ $EXIT_CODE -eq 0 ]; then
  log_success "All infrastructure checks passed!"
else
  log_failure "Some infrastructure checks failed."
fi

exit $EXIT_CODE