#!/usr/bin/env bash
# Stop all DBIS Core services gracefully

set -euo pipefail

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
PROJECT_ROOT="$(cd "$SCRIPT_DIR/../../.." && pwd)"

# Source utilities
source "$PROJECT_ROOT/dbis_core/scripts/utils/common.sh"

# Load configuration
load_config

log_info "========================================="
log_info "DBIS Core - Stop Services"
log_info "========================================="
log_info ""

check_root
if ! command_exists pct; then
    error_exit "This script must be run on Proxmox host (pct command not found)"
fi

# Stop containers in reverse order
log_info "Stopping containers..."

# Stop Frontend
if pct list | grep -q "^\s*${VMID_DBIS_FRONTEND:-10130}\s"; then
    log_info "Stopping Frontend..."
    pct stop "${VMID_DBIS_FRONTEND:-10130}" 2>/dev/null || log_warn "Frontend may already be stopped"
    sleep 2
fi

# Stop API
if pct list | grep -q "^\s*${VMID_DBIS_API_PRIMARY:-10150}\s"; then
    log_info "Stopping API Primary..."
    pct stop "${VMID_DBIS_API_PRIMARY:-10150}" 2>/dev/null || log_warn "API may already be stopped"
    sleep 2
fi

# Stop Redis
if pct list | grep -q "^\s*${VMID_DBIS_REDIS:-10120}\s"; then
    log_info "Stopping Redis..."
    pct stop "${VMID_DBIS_REDIS:-10120}" 2>/dev/null || log_warn "Redis may already be stopped"
    sleep 2
fi

# Stop PostgreSQL (last)
if pct list | grep -q "^\s*${VMID_DBIS_POSTGRES_PRIMARY:-10100}\s"; then
    log_info "Stopping PostgreSQL Primary..."
    pct stop "${VMID_DBIS_POSTGRES_PRIMARY:-10100}" 2>/dev/null || log_warn "PostgreSQL may already be stopped"
    sleep 2
fi

log_info ""
log_success "Services stopped!"
log_info ""
log_info "Run './scripts/management/start-services.sh' to start services again"

