#!/usr/bin/env bash
# DBIS Core specific utility functions

# Source common utilities
if [[ -f "$(dirname "${BASH_SOURCE[0]}")/common.sh" ]]; then
    source "$(dirname "${BASH_SOURCE[0]}")/common.sh"
fi

# Validate environment variables
validate_env_vars() {
    local required_vars=("$@")
    local missing_vars=()
    
    for var in "${required_vars[@]}"; do
        if [[ -z "${!var:-}" ]]; then
            missing_vars+=("$var")
        fi
    done
    
    if [[ ${#missing_vars[@]} -gt 0 ]]; then
        log_error "Missing required environment variables: ${missing_vars[*]}"
        return 1
    fi
    return 0
}

# Test database connection
test_database_connection() {
    local vmid="$1"
    local db_host="${2:-192.168.11.100}"
    local db_port="${3:-5432}"
    local db_name="${4:-dbis_core}"
    local db_user="${5:-dbis}"
    
    log_info "Testing database connection to $db_host:$db_port..."
    
    if pct exec "$vmid" -- bash -c "command -v psql >/dev/null 2>&1" 2>/dev/null; then
        if pct exec "$vmid" -- bash -c "PGPASSWORD=\${DB_PASSWORD:-} psql -h $db_host -p $db_port -U $db_user -d $db_name -c 'SELECT 1;' >/dev/null 2>&1" 2>/dev/null; then
            log_success "Database connection successful"
            return 0
        fi
    fi
    
    log_warn "Database connection test failed (psql may not be installed in container)"
    return 1
}

# Test Redis connection
test_redis_connection() {
    local vmid="$1"
    local redis_host="${2:-192.168.11.125}"
    local redis_port="${3:-6379}"
    
    log_info "Testing Redis connection to $redis_host:$redis_port..."
    
    if pct exec "$vmid" -- bash -c "command -v redis-cli >/dev/null 2>&1" 2>/dev/null; then
        if pct exec "$vmid" -- bash -c "redis-cli -h $redis_host -p $redis_port ping >/dev/null 2>&1" 2>/dev/null; then
            log_success "Redis connection successful"
            return 0
        fi
    fi
    
    log_warn "Redis connection test failed (redis-cli may not be installed in container)"
    return 1
}

# Test API health endpoint
test_api_health() {
    local api_host="${1:-192.168.11.150}"
    local api_port="${2:-3000}"
    
    log_info "Testing API health endpoint at http://$api_host:$api_port/health..."
    
    if command_exists curl; then
        if curl -s -f "http://$api_host:$api_port/health" >/dev/null 2>&1; then
            log_success "API health check passed"
            return 0
        fi
    fi
    
    log_warn "API health check failed"
    return 1
}

# Check service status in container
check_service_status() {
    local vmid="$1"
    local service_name="$2"
    
    if pct exec "$vmid" -- systemctl is-active --quiet "$service_name" 2>/dev/null; then
        return 0
    fi
    return 1
}

# Get service logs
get_service_logs() {
    local vmid="$1"
    local service_name="$2"
    local lines="${3:-50}"
    
    pct exec "$vmid" -- journalctl -u "$service_name" -n "$lines" --no-pager 2>/dev/null || {
        log_warn "Failed to get logs for service $service_name"
        return 1
    }
}

# Wait for service to be ready
wait_for_service() {
    local vmid="$1"
    local service_name="$2"
    local max_wait="${3:-60}"
    local waited=0
    
    log_info "Waiting for service $service_name to be ready..."
    
    while [[ $waited -lt $max_wait ]]; do
        if check_service_status "$vmid" "$service_name"; then
            log_success "Service $service_name is ready"
            return 0
        fi
        sleep 2
        waited=$((waited + 2))
    done
    
    log_error "Service $service_name not ready after ${max_wait}s"
    return 1
}

# Generate JWT secret
generate_jwt_secret() {
    openssl rand -hex 32 2>/dev/null || {
        # Fallback to /dev/urandom
        head -c 32 /dev/urandom | base64 | tr -d '\n'
    }
}

# Validate JWT secret
validate_jwt_secret() {
    local secret="$1"
    
    if [[ ${#secret} -lt 32 ]]; then
        log_error "JWT secret must be at least 32 characters"
        return 1
    fi
    return 0
}

# Create database user
create_database_user() {
    local vmid="$1"
    local db_user="${2:-dbis}"
    local db_password="${3:-}"
    
    if [[ -z "$db_password" ]]; then
        log_error "Database password required"
        return 1
    fi
    
    log_info "Creating database user $db_user..."
    
    pct exec "$vmid" -- bash -c "sudo -u postgres psql -c \"CREATE USER $db_user WITH PASSWORD '$db_password';\" 2>/dev/null" || {
        log_warn "User $db_user may already exist"
    }
    
    pct exec "$vmid" -- bash -c "sudo -u postgres psql -c \"ALTER USER $db_user CREATEDB;\" 2>/dev/null" || true
    
    log_success "Database user $db_user created"
    return 0
}

# Create database
create_database() {
    local vmid="$1"
    local db_name="${2:-dbis_core}"
    local db_user="${3:-dbis}"
    
    log_info "Creating database $db_name..."
    
    pct exec "$vmid" -- bash -c "sudo -u postgres psql -c \"CREATE DATABASE $db_name OWNER $db_user;\" 2>/dev/null" || {
        log_warn "Database $db_name may already exist"
    }
    
    log_success "Database $db_name created"
    return 0
}

