#!/usr/bin/env bash
# Master deployment script for DBIS Core Banking System
# Orchestrates deployment of all services in correct order

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 - Complete Deployment"
log_info "========================================="
log_info ""

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

# Deployment flags
DEPLOY_POSTGRESQL="${DEPLOY_POSTGRESQL:-true}"
DEPLOY_REDIS="${DEPLOY_REDIS:-true}"
DEPLOY_API="${DEPLOY_API:-true}"
DEPLOY_FRONTEND="${DEPLOY_FRONTEND:-true}"

# Track deployment status
DEPLOYMENT_SUCCESS=true
FAILED_SERVICES=()

# Function to deploy service with error handling
deploy_service() {
    local service_name="$1"
    local script_path="$2"
    
    log_info "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
    log_info "Deploying: $service_name"
    log_info "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
    
    if [[ ! -f "$script_path" ]]; then
        log_error "Deployment script not found: $script_path"
        DEPLOYMENT_SUCCESS=false
        FAILED_SERVICES+=("$service_name (script not found)")
        return 1
    fi
    
    if bash "$script_path"; then
        log_success "$service_name deployed successfully"
        return 0
    else
        log_error "$service_name deployment failed"
        DEPLOYMENT_SUCCESS=false
        FAILED_SERVICES+=("$service_name")
        return 1
    fi
}

# Phase 1: Foundation Services
log_info "Phase 1: Deploying Foundation Services"
log_info ""

if [[ "$DEPLOY_POSTGRESQL" == "true" ]]; then
    deploy_service "PostgreSQL" "$SCRIPT_DIR/deploy-postgresql.sh" || {
        log_warn "PostgreSQL deployment failed, but continuing..."
    }
    log_info ""
fi

if [[ "$DEPLOY_REDIS" == "true" ]]; then
    deploy_service "Redis" "$SCRIPT_DIR/deploy-redis.sh" || {
        log_warn "Redis deployment failed, but continuing..."
    }
    log_info ""
fi

# Wait for foundation services to be ready
log_info "Waiting for foundation services to be ready..."
sleep 10

# Phase 2: Application Services
log_info "Phase 2: Deploying Application Services"
log_info ""

if [[ "$DEPLOY_API" == "true" ]]; then
    deploy_service "API" "$SCRIPT_DIR/deploy-api.sh" || {
        log_warn "API deployment failed, but continuing..."
    }
    log_info ""
fi

if [[ "$DEPLOY_FRONTEND" == "true" ]]; then
    deploy_service "Frontend" "$SCRIPT_DIR/deploy-frontend.sh" || {
        log_warn "Frontend deployment failed, but continuing..."
    }
    log_info ""
fi

# Deployment Summary
log_info "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
log_info "Deployment Summary"
log_info "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
log_info ""

if [[ "$DEPLOYMENT_SUCCESS" == "true" ]]; then
    log_success "All services deployed successfully!"
    log_info ""
    log_info "Service Endpoints:"
    log_info "  PostgreSQL: ${DBIS_POSTGRES_PRIMARY_IP:-192.168.11.100}:5432"
    log_info "  Redis: ${DBIS_REDIS_IP:-192.168.11.125}:6379"
    log_info "  API: http://${DBIS_API_PRIMARY_IP:-192.168.11.150}:${DBIS_API_PORT:-3000}"
    log_info "  Frontend: http://${DBIS_FRONTEND_IP:-192.168.11.130}"
    log_info ""
    log_info "Next Steps:"
    log_info "1. Run database migrations: ./scripts/deployment/configure-database.sh"
    log_info "2. Check service status: ./scripts/management/status.sh"
    log_info "3. Test API health: curl http://${DBIS_API_PRIMARY_IP:-192.168.11.150}:${DBIS_API_PORT:-3000}/health"
else
    log_error "Deployment completed with errors!"
    log_info ""
    log_info "Failed Services:"
    for service in "${FAILED_SERVICES[@]}"; do
        log_error "  - $service"
    done
    log_info ""
    log_info "Please review the errors above and retry failed deployments."
    exit 1
fi

