package com.cameleer.server.app.runtime;

import com.github.dockerjava.api.DockerClient;
import com.github.dockerjava.api.model.Network;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.List;

public class DockerNetworkManager {

    private static final Logger log = LoggerFactory.getLogger(DockerNetworkManager.class);
    public static final String TRAEFIK_NETWORK = "cameleer-traefik";
    public static final String ENV_NETWORK_PREFIX = "cameleer-env-";

    private final DockerClient dockerClient;

    public DockerNetworkManager(DockerClient dockerClient) {
        this.dockerClient = dockerClient;
    }

    public String ensureNetwork(String networkName) {
        List<Network> existing = dockerClient.listNetworksCmd()
                .withNameFilter(networkName)
                .exec();

        for (Network net : existing) {
            if (net.getName().equals(networkName)) {
                return net.getId();
            }
        }

        String id = dockerClient.createNetworkCmd()
                .withName(networkName)
                .withDriver("bridge")
                .withCheckDuplicate(true)
                .exec()
                .getId();

        log.info("Created Docker network: {} ({})", networkName, id);
        return id;
    }

    public void connectContainer(String containerId, String networkName) {
        String networkId = ensureNetwork(networkName);
        try {
            dockerClient.connectToNetworkCmd()
                    .withContainerId(containerId)
                    .withNetworkId(networkId)
                    .exec();
            log.debug("Connected container {} to network {}", containerId, networkName);
        } catch (Exception e) {
            if (!e.getMessage().contains("already exists")) {
                throw e;
            }
        }
    }

    public static String envNetworkName(String envSlug) {
        return ENV_NETWORK_PREFIX + envSlug;
    }

    /** Tenant-scoped environment network name to prevent cross-tenant collisions. */
    public static String envNetworkName(String tenantId, String envSlug) {
        return ENV_NETWORK_PREFIX + tenantId + "-" + envSlug;
    }
}
