<?php
require_once __DIR__ . '/valkey-mgmt.php';
require_once __DIR__ . '/docker-api.php';

/**
 * Attach a newly created container to its customer's Valkey network if enabled.
 * No-op when the customer does not have Valkey.
 * Non-fatal on failure — the UI surfaces a "not connected" badge.
 */
function whp_valkey_attach_if_enabled(PDO $db, $username, $container_name) {
    $vk = new ValkeyMgr($db);
    $row = $vk->get_row($username);
    if (!$row || intval($row['enabled']) !== 1) {
        return ['attached' => false, 'error' => null];
    }
    $docker = new DockerAPI();
    $r = $docker->connect_network($row['network_name'], $container_name);
    if (!$r['success']) {
        error_log("valkey attach failed for $container_name -> {$row['network_name']}: " . ($r['error'] ?? ''));
        return ['attached' => false, 'error' => $r['error'] ?? 'attach failed'];
    }
    return ['attached' => true, 'error' => null];
}
