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

SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"
export KUBECONFIG="$SCRIPT_DIR/../env/frigo-dev.yaml"

TAG="${1:-latest}"

DB_USER="wksp_ai"
DB_PASS="s!)löyx209aasgtrasdasiudkash5235FDSXljLJ"
DB_HOST="10.75.10.171"
DB_PORT="32710"
DB_SID="freepdb1"
DB_CONNECT="${DB_USER}/${DB_PASS}@${DB_HOST}:${DB_PORT}/${DB_SID}"

echo "=== dc-backend Update ==="
echo ""

# --- DB Migration ---
echo "→ [1/4] DB Migration..."
sql -s "$DB_CONNECT" @"$SCRIPT_DIR/../Scripts/DC_DOCUMENT_PROGRESS_ALTER.sql"
sql -s "$DB_CONNECT" @"$SCRIPT_DIR/../Scripts/DC_DOCUMENT_PROGRESS_ORDS.sql"
sql -s "$DB_CONNECT" @"$SCRIPT_DIR/../Scripts/DC_REFERENCES_ALTER.sql"
echo "✓ DB Migration abgeschlossen."

# --- Build & Push ---
echo ""
echo "→ [2/4] Build & Push Image (Tag: $TAG)..."
bash "$SCRIPT_DIR/build-and-push.sh" "$TAG"

# --- Apply Kubernetes Manifests ---
echo ""
echo "→ [3/4] Kubernetes Manifests anwenden..."
kubectl apply -f "$SCRIPT_DIR/k8s/deployment.yaml"

# --- Rolling Restart (zieht neues 'latest'-Image) ---
echo ""
echo "→ [4/4] Rolling Restart..."
kubectl rollout restart deployment/dc-backend -n ai-env

echo ""
echo "→ Warte auf Rollout..."
kubectl rollout status deployment/dc-backend -n ai-env --timeout=120s

echo ""
echo "✓ Deployment abgeschlossen."
echo ""
kubectl get pods -n ai-env -l app=dc-backend
