import { Resource } from "../resource.js";
import { DockerApi } from "./api.js";
/**
 * Create and manage a Docker Network
 *
 * @see https://docs.docker.com/engine/network/
 *
 * @example
 * // Create a simple bridge network
 * const appNetwork = await Network("app-network", {
 *   name: "app-network"
 * });
 *
 * @example
 * // Create a custom network with driver
 * const overlayNetwork = await Network("overlay-network", {
 *   name: "overlay-network",
 *   driver: "overlay",
 *   enableIPv6: true,
 *   labels: {
 *     "com.example.description": "Network for application services"
 *   }
 * });
 */
export const Network = Resource("docker::Network", async function (id, props) {
    // Initialize Docker API client
    const api = new DockerApi();
    const networkName = props.name ?? this.output?.name ?? this.scope.createPhysicalName(id);
    if (this.phase === "update" && this.output.name !== networkName) {
        this.replace();
    }
    // Handle delete phase
    if (this.phase === "delete") {
        if (this.output?.id) {
            // Remove network
            await api.removeNetwork(this.output.id);
        }
        // Return destroyed state
        return this.destroy();
    }
    else {
        // Create the network
        props.driver = props.driver || "bridge";
        try {
            const networkId = await api.createNetwork(networkName, props.driver);
            return {
                ...props,
                id: networkId,
                name: networkName,
                createdAt: Date.now(),
            };
        }
        catch (error) {
            const errorMessage = error.message || String(error);
            if (errorMessage.includes(`network with name ${networkName} already exists`)) {
                const [details] = await api.inspectNetwork(networkName);
                if (details) {
                    return {
                        ...props,
                        id: details.Id,
                        name: networkName,
                        createdAt: Date.parse(details.Created) || Date.now(),
                    };
                }
            }
            throw error;
        }
    }
});
//# sourceMappingURL=network.js.map