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

BACKEND_DIR="$(cd "$(dirname "$0")/../backend" && pwd)"
FRONTEND_DIR="$(cd "$(dirname "$0")/../frontend" && pwd)"
API_DOCS_URL="http://localhost:8080/api-docs"
TIMEOUT=60
BACKEND_PID=""

cleanup() {
  if [[ -n "$BACKEND_PID" ]]; then
    echo "→ Backend wird gestoppt (PID $BACKEND_PID)..."
    kill "$BACKEND_PID" 2>/dev/null || true
  fi
}
trap cleanup EXIT

wait_for_backend() {
  echo "→ Warte auf Backend ($TIMEOUT s)..."
  local elapsed=0
  until curl -sf "$API_DOCS_URL" -o /dev/null; do
    if (( elapsed >= TIMEOUT )); then
      echo "✗ Backend nicht erreichbar nach ${TIMEOUT}s" >&2
      exit 1
    fi
    sleep 2
    (( elapsed += 2 ))
  done
  echo "✓ Backend bereit"
}

# Backend starten falls nicht erreichbar
if curl -sf "$API_DOCS_URL" -o /dev/null 2>/dev/null; then
  echo "✓ Backend läuft bereits"
else
  echo "→ Backend wird gestartet..."
  mvn -f "$BACKEND_DIR/pom.xml" spring-boot:run -Dspring-boot.run.profiles=no-db -q &
  BACKEND_PID=$!
  wait_for_backend
fi

echo "→ OpenAPI-Spec wird generiert..."
curl -sf "$API_DOCS_URL" -o "$FRONTEND_DIR/openapi.json"
echo "✓ openapi.json aktualisiert"

echo "→ TypeScript-Typen werden generiert..."
pnpm --filter @effigenix/types --prefix "$FRONTEND_DIR" generate:types
echo "✓ src/generated/api.ts aktualisiert"

echo ""
echo "Fertig. Bitte committen:"
echo "  git add frontend/openapi.json frontend/packages/types/src/generated/api.ts"
