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

NAMESPACE="honeydue"

log() { printf '[rollback] %s\n' "$*"; }
die() { printf '[rollback][error] %s\n' "$*" >&2; exit 1; }

command -v kubectl >/dev/null 2>&1 || die "Missing: kubectl"

DEPLOYMENTS=("api" "worker" "admin")

# --- Show current state ---

echo "=== Current Rollout History ==="
for deploy in "${DEPLOYMENTS[@]}"; do
  echo ""
  echo "--- ${deploy} ---"
  kubectl rollout history deployment/"${deploy}" -n "${NAMESPACE}" 2>/dev/null || echo "  (not found)"
done

echo ""
echo "=== Current Images ==="
for deploy in "${DEPLOYMENTS[@]}"; do
  IMAGE="$(kubectl get deployment "${deploy}" -n "${NAMESPACE}" -o jsonpath='{.spec.template.spec.containers[0].image}' 2>/dev/null || echo "n/a")"
  echo "  ${deploy}: ${IMAGE}"
done

# --- Confirm ---

echo ""
read -rp "Roll back all deployments to previous revision? [y/N] " confirm
if [[ "${confirm}" != "y" && "${confirm}" != "Y" ]]; then
  log "Aborted."
  exit 0
fi

# --- Rollback ---

for deploy in "${DEPLOYMENTS[@]}"; do
  log "Rolling back ${deploy}..."
  kubectl rollout undo deployment/"${deploy}" -n "${NAMESPACE}" 2>/dev/null || log "Skipping ${deploy} (not found or no previous revision)"
done

# --- Wait ---

log "Waiting for rollouts..."
for deploy in "${DEPLOYMENTS[@]}"; do
  kubectl rollout status deployment/"${deploy}" -n "${NAMESPACE}" --timeout=300s 2>/dev/null || true
done

# --- Verify ---

echo ""
echo "=== Post-Rollback Images ==="
for deploy in "${DEPLOYMENTS[@]}"; do
  IMAGE="$(kubectl get deployment "${deploy}" -n "${NAMESPACE}" -o jsonpath='{.spec.template.spec.containers[0].image}' 2>/dev/null || echo "n/a")"
  echo "  ${deploy}: ${IMAGE}"
done

log "Rollback complete. Run ./scripts/04-verify.sh to check health."
