#!/usr/bin/env bash
set -euo pipefail

ROOT_DIR=$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")/.." && pwd)
COMPOSE_DIR="$ROOT_DIR/infra/compose"

get_env() {
  local key="$1"; local def="${2-}"
  local line
  line=$(grep -E "^${key}=" "$COMPOSE_DIR/.env" | tail -n1 || true)
  if [[ -z "$line" ]]; then printf "%s" "$def"; return; fi
  printf "%s" "${line#*=}"
}

DOMAIN=${DOMAIN:-$(get_env DOMAIN local)}

echo "🔎 Verifying core infra endpoints for domain: $DOMAIN..."

check() {
  local name="$1" url="$2"
  code=$(curl -ks -o /dev/null -w '%{http_code}' "$url" || true)
  if [[ "$code" == "200" || "$code" == "302" || "$code" == "401" ]]; then
    echo "✅ $name ($url) -> $code"
  else
    echo "❌ $name ($url) -> $code"; return 1
  fi
}

ok=true
check Traefik "http://localhost:8080/ping" || ok=false
check Authentik "https://auth.${DOMAIN}/if/flow/default-authentication-flow/" || ok=false
check Grafana "https://grafana.${DOMAIN}" || ok=false
check Unleash "https://unleash.${DOMAIN}" || ok=false
check Neo4j "https://neo4j.${DOMAIN}" || ok=false
check Qdrant "https://qdrant.${DOMAIN}/health" || ok=false
check Vault "https://vault.${DOMAIN}/v1/sys/health" || ok=false
check Minio "https://minio.${DOMAIN}" || ok=false

if [[ "$ok" == true ]]; then
  echo "🎉 Infra endpoints reachable"
else
  echo "⚠️ Some checks failed. Use 'make logs' or 'make logs-service SERVICE=name'"
  exit 1
fi
