package com.cameleer.server.app.runtime;

import com.cameleer.server.core.runtime.ResolvedContainerConfig;

import java.util.LinkedHashMap;
import java.util.Map;

public final class TraefikLabelBuilder {

    private TraefikLabelBuilder() {}

    public static Map<String, String> build(String appSlug, String envSlug, String tenantId,
                                              ResolvedContainerConfig config, int replicaIndex,
                                              String generation) {
        // Traefik router/service keys stay generation-agnostic so load balancing
        // spans old + new replicas during a blue/green overlap. instance-id and
        // the new generation label carry the per-deploy identity.
        String svc = envSlug + "-" + appSlug;
        String instanceId = envSlug + "-" + appSlug + "-" + replicaIndex + "-" + generation;
        Map<String, String> labels = new LinkedHashMap<>();

        labels.put("managed-by", "cameleer-server");
        labels.put("cameleer.tenant", tenantId);
        labels.put("cameleer.app", appSlug);
        labels.put("cameleer.environment", envSlug);
        labels.put("cameleer.replica", String.valueOf(replicaIndex));
        labels.put("cameleer.generation", generation);
        labels.put("cameleer.instance-id", instanceId);

        if (!config.externalRouting()) {
            return labels;
        }

        labels.put("traefik.enable", "true");
        labels.put("traefik.http.services." + svc + ".loadbalancer.server.port",
                String.valueOf(config.appPort()));

        if ("subdomain".equals(config.routingMode())) {
            labels.put("traefik.http.routers." + svc + ".rule",
                    "Host(`" + appSlug + "-" + envSlug + "." + config.routingDomain() + "`)");
        } else {
            labels.put("traefik.http.routers." + svc + ".rule",
                    "PathPrefix(`/" + envSlug + "/" + appSlug + "/`)");

            if (config.stripPathPrefix()) {
                labels.put("traefik.http.middlewares." + svc + "-strip.stripprefix.prefixes",
                        "/" + envSlug + "/" + appSlug);
                labels.put("traefik.http.routers." + svc + ".middlewares",
                        svc + "-strip");
            }
        }

        labels.put("traefik.http.routers." + svc + ".entrypoints",
                config.sslOffloading() ? "websecure" : "web");

        if (config.sslOffloading()) {
            labels.put("traefik.http.routers." + svc + ".tls", "true");
            if (config.certResolver() != null && !config.certResolver().isBlank()) {
                labels.put("traefik.http.routers." + svc + ".tls.certresolver",
                        config.certResolver());
            }
        }

        return labels;
    }
}
