package server.debug;

import jakarta.servlet.Servlet;
import org.eclipse.jetty.servlet.ServletContextHandler;
import org.eclipse.jetty.servlet.ServletHolder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import utils.config.AppConfig;

/**
 * Регистрирует HTTP debug endpoints.
 */
public final class DebugApiConfigurator {

    private static final Logger log = LoggerFactory.getLogger(DebugApiConfigurator.class);
    private static final String CFG_DEBUG_API_ENABLED = "debug.tempApi.enabled";

    private DebugApiConfigurator() {
    }

    public static void register(ServletContextHandler context) {
        boolean enabled = AppConfig.getInstance().getBoolean(CFG_DEBUG_API_ENABLED, false);
        if (!enabled) {
            log.warn("⚠️ Debug API отключены настройкой {}=false", CFG_DEBUG_API_ENABLED);
            return;
        }

        DebugTokenProvider tokenProvider = DebugTokenProvider.loadFromProjectRoot();

        addServlet(context, new DebugClientsServlet(tokenProvider), "/debug/ws/clients");
        addServlet(context, new DebugConnectServlet(tokenProvider), "/debug/ws/connect");
        addServlet(context, new DebugLogsServlet(tokenProvider), "/debug/ws/logs");
        addServlet(context, new DebugUiReloadAllServlet(tokenProvider), "/debug/ws/ui-reload-all");
        log.info("✅ Debug API включены настройкой {}=true", CFG_DEBUG_API_ENABLED);
    }

    private static void addServlet(ServletContextHandler context, Servlet servlet, String path) {
        ServletHolder holder = new ServletHolder(servlet);
        context.addServlet(holder, path);
    }
}
