#!/usr/bin/env bash
# Deploy PostgreSQL Database Containers for DBIS Core Banking System

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"
source "$PROJECT_ROOT/dbis_core/scripts/utils/dbis-core-utils.sh" 2>/dev/null || true
source "$PROJECT_ROOT/smom-dbis-138-proxmox/lib/container-utils.sh" 2>/dev/null || true

# Load configuration
load_config

log_info "========================================="
log_info "DBIS Core - PostgreSQL Deployment"
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

# Ensure OS template exists
ensure_os_template "${DBIS_CONTAINER_OS_TEMPLATE:-${CONTAINER_OS_TEMPLATE:-local:vztmpl/ubuntu-22.04-standard_22.04-1_amd64.tar.zst}}" || {
    error_exit "OS template not available. Please download it first."
}

# Function to create PostgreSQL container
create_postgresql_container() {
    local vmid="$1"
    local hostname="$2"
    local ip_address="$3"
    local is_replica="${4:-false}"
    
    log_info "Creating PostgreSQL container: $hostname (VMID: $vmid, IP: $ip_address)"
    
    if container_exists "$vmid"; then
        log_warn "Container $vmid already exists, skipping creation"
    else
        log_info "Creating container $vmid..."
        pct create "$vmid" \
            "${DBIS_CONTAINER_OS_TEMPLATE:-${CONTAINER_OS_TEMPLATE:-local:vztmpl/ubuntu-22.04-standard_22.04-1_amd64.tar.zst}}" \
            --storage "${PROXMOX_STORAGE:-local-lvm}" \
            --hostname "$hostname" \
            --memory "${DBIS_POSTGRES_MEMORY:-8192}" \
            --cores "${DBIS_POSTGRES_CORES:-4}" \
            --rootfs "${PROXMOX_STORAGE:-local-lvm}:${DBIS_POSTGRES_DISK:-200}" \
            --net0 "bridge=${DBIS_NETWORK_BRIDGE:-vmbr0},name=eth0,ip=${ip_address}/24,gw=192.168.11.1,type=veth" \
            --unprivileged "${DBIS_CONTAINER_UNPRIVILEGED:-1}" \
            --swap "${DBIS_POSTGRES_SWAP:-1024}" \
            --onboot "${DBIS_CONTAINER_ONBOOT:-1}" \
            --timezone "${DBIS_CONTAINER_TIMEZONE:-America/Los_Angeles}" \
            --features nesting=1,keyctl=1
        
        log_success "Container $vmid created"
    fi
    
    wait_for_container "$vmid"
    
    # Configure container
    log_info "Configuring container $vmid..."
    pct set "$vmid" --features nesting=1,keyctl=1
    
    # Start container and wait for readiness
    if ! start_container_and_wait "$vmid"; then
        log_error "Failed to start container $vmid"
        return 1
    fi
    
    # Verify container is ready
    if ! verify_container_ready "$vmid"; then
        log_error "Container $vmid is not ready for file operations"
        return 1
    fi
    
    # Configure locale
    pct exec "$vmid" -- bash -c "export LC_ALL=C; export LANG=C; echo 'export LC_ALL=C' >> /root/.bashrc; echo 'export LANG=C' >> /root/.bashrc; echo 'export LC_ALL=C' >> /etc/environment; echo 'export LANG=C' >> /etc/environment" 2>/dev/null || true
    
    # Update system
    log_info "Updating system packages..."
    pct exec "$vmid" -- bash -c "export DEBIAN_FRONTEND=noninteractive; apt-get update -qq && apt-get upgrade -y -qq" 2>&1 | grep -vE "(perl: warning|locale:)" || true
    
    # Install PostgreSQL
    log_info "Installing PostgreSQL ${DBIS_POSTGRES_VERSION:-15}..."
    pct exec "$vmid" -- bash -c "export DEBIAN_FRONTEND=noninteractive; apt-get install -y -qq postgresql-${DBIS_POSTGRES_VERSION:-15} postgresql-contrib-${DBIS_POSTGRES_VERSION:-15}" 2>&1 | grep -vE "(perl: warning|locale:)" || {
        log_error "Failed to install PostgreSQL"
        return 1
    }
    
    # Configure PostgreSQL
    log_info "Configuring PostgreSQL..."
    
    # Set PostgreSQL to listen on all interfaces
    pct exec "$vmid" -- bash -c "sed -i \"s/#listen_addresses = 'localhost'/listen_addresses = '*'/\" /etc/postgresql/${DBIS_POSTGRES_VERSION:-15}/main/postgresql.conf" 2>/dev/null || true
    
    # Configure pg_hba.conf to allow connections from API containers
    pct exec "$vmid" -- bash -c "echo 'host    all             all             192.168.11.0/24           md5' >> /etc/postgresql/${DBIS_POSTGRES_VERSION:-15}/main/pg_hba.conf" 2>/dev/null || true
    
    # Restart PostgreSQL
    log_info "Starting PostgreSQL service..."
    pct exec "$vmid" -- systemctl restart postgresql 2>/dev/null || true
    pct exec "$vmid" -- systemctl enable postgresql 2>/dev/null || true
    
    # Wait for PostgreSQL to be ready
    log_info "Waiting for PostgreSQL to be ready..."
    sleep 5
    
    # Create database and user (only for primary)
    if [[ "$is_replica" != "true" ]]; then
        local db_name="${DBIS_DB_NAME:-dbis_core}"
        local db_user="${DBIS_DB_USER:-dbis}"
        local db_password="${DBIS_DB_PASSWORD:-}"
        
        if [[ -z "$db_password" ]]; then
            log_warn "DBIS_DB_PASSWORD not set, generating random password..."
            db_password=$(generate_jwt_secret)
        fi
        
        log_info "Creating database and user..."
        create_database_user "$vmid" "$db_user" "$db_password"
        create_database "$vmid" "$db_name" "$db_user"
        
        log_info "Database credentials:"
        log_info "  Database: $db_name"
        log_info "  User: $db_user"
        log_info "  Password: $db_password"
        log_warn "Save these credentials securely!"
    fi
    
    # Configure firewall (if ufw is available)
    if pct exec "$vmid" -- command -v ufw >/dev/null 2>&1; then
        log_info "Configuring firewall..."
        pct exec "$vmid" -- bash -c "ufw allow 5432/tcp comment 'PostgreSQL'" 2>/dev/null || true
    fi
    
    log_success "PostgreSQL container $hostname (VMID: $vmid) deployed successfully"
    return 0
}

# Deploy PostgreSQL Primary
log_info "Deploying PostgreSQL Primary..."
create_postgresql_container \
    "${VMID_DBIS_POSTGRES_PRIMARY:-10100}" \
    "dbis-postgres-primary" \
    "${DBIS_POSTGRES_PRIMARY_IP:-192.168.11.100}" \
    "false"

# Deploy PostgreSQL Replica (if enabled)
if [[ "${DBIS_POSTGRES_REPLICA_COUNT:-0}" -gt 0 ]]; then
    log_info "Deploying PostgreSQL Replica..."
    create_postgresql_container \
        "${VMID_DBIS_POSTGRES_REPLICA:-10101}" \
        "dbis-postgres-replica-1" \
        "${DBIS_POSTGRES_REPLICA_IP:-192.168.11.101}" \
        "true"
fi

log_success "PostgreSQL deployment completed!"
log_info ""
log_info "Next steps:"
log_info "1. Run database migrations: ./scripts/deployment/configure-database.sh"
log_info "2. Deploy Redis: ./scripts/deployment/deploy-redis.sh"
log_info "3. Deploy API: ./scripts/deployment/deploy-api.sh"

