#!/bin/bash
# Nexus Deployment Script
# Auf dem VPS-HOST ausführen, nicht im Container!
set -e

SCRIPT_DIR="$(dirname "$(readlink -f "$0")")"
NEXUS_DIR="$(dirname "$SCRIPT_DIR")"

echo "=== Nexus Deployment ==="
echo "Verzeichnis: $NEXUS_DIR"

cd "$NEXUS_DIR"

echo ""
echo "[1/4] Prüfe Konfiguration..."
docker compose config --quiet && echo "  ✅ Konfiguration gültig"

echo ""
echo "[2/4] Starte Stack (mit Healthchecks)..."
docker compose up -d --wait

echo ""
echo "[3/4] Status nach Deployment..."
docker compose ps

echo ""
echo "[4/4] Verifikation..."
check_code() {
  local path="$1"
  curl -s -o /dev/null -w "%{http_code}" "http://localhost:18880${path}"
}

HEALTH_CODE=$(check_code /health)
DASHBOARD_CODE=$(check_code /dashboard)
OPS_CODE=$(check_code /api/v1/operations/snapshot)

if [ "$HEALTH_CODE" = "200" ] && [ "$DASHBOARD_CODE" != "200" ]; then
  WEB_CID="$(docker compose ps -q web || true)"
  if [ -n "$WEB_CID" ]; then
    WEB_STATE="$(docker inspect -f '{{.State.Status}}' "$WEB_CID" 2>/dev/null || true)"
    if [ "$WEB_STATE" = "created" ]; then
      echo "  ℹ️  API healthy, aber web noch im Status 'created' — starte web nach"
      docker compose up -d web
      sleep 2
      DASHBOARD_CODE=$(check_code /dashboard)
      OPS_CODE=$(check_code /api/v1/operations/snapshot)
    fi
  fi
fi

echo "  /health                     -> ${HEALTH_CODE}"
echo "  /dashboard                  -> ${DASHBOARD_CODE}"
echo "  /api/v1/operations/snapshot -> ${OPS_CODE}"

if [ "$HEALTH_CODE" != "200" ] || [ "$DASHBOARD_CODE" != "200" ] || [ "$OPS_CODE" != "401" ]; then
  echo "  ❌ Verifikation fehlgeschlagen"
  exit 1
fi

echo "  ✅ Health-Check bestanden"
echo "  ✅ Dashboard erreichbar"
echo "  ✅ Operations API fordert Auth an"

echo ""
echo "=== Deployment abgeschlossen ==="
echo "Dashboard:  https://nexus.noveria.net/dashboard"
echo "Health-API: https://nexus.noveria.net/health"
echo ""
echo "Login-Informationen: docker compose logs api | grep 'Initial owner'"
echo "Status:             docker compose ps"
