package server.logic.ws_protocol.JSON.handlers.system;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import server.logic.ws_protocol.JSON.ConnectionContext;
import server.logic.ws_protocol.JSON.debug.DebugRunLogBuffer;
import server.logic.ws_protocol.JSON.entyties.Net_Request;
import server.logic.ws_protocol.JSON.entyties.Net_Response;
import server.logic.ws_protocol.JSON.handlers.JsonMessageHandler;
import server.logic.ws_protocol.JSON.handlers.system.entyties.Net_ClientDebugLog_Request;
import server.logic.ws_protocol.JSON.handlers.system.entyties.Net_ClientDebugLog_Response;
import server.logic.ws_protocol.JSON.utils.NetExceptionResponseFactory;
import server.logic.ws_protocol.WireCodes;

public class Net_ClientDebugLog_Handler implements JsonMessageHandler {
    private static final Logger log = LoggerFactory.getLogger(Net_ClientDebugLog_Handler.class);

    @Override
    public Net_Response handle(Net_Request baseRequest, ConnectionContext ctx) {
        Net_ClientDebugLog_Request req = (Net_ClientDebugLog_Request) baseRequest;
        String message = safe(req.getMessage());
        if (message.isBlank()) {
            return NetExceptionResponseFactory.error(req, WireCodes.Status.BAD_REQUEST, "BAD_FIELDS", "Поле message обязательно");
        }

        String runId = safe(req.getRunId());
        String level = safe(req.getLevel());
        String sessionId = safe(ctx != null ? ctx.getSessionId() : "");
        String login = safe(ctx != null ? ctx.getLogin() : "");
        String details = safe(req.getDetails());

        DebugRunLogBuffer.getInstance().add(level, runId, "client", sessionId, login, message, details);

        log.info("CLIENT_DEBUG runId={} level={} login={} sessionId={} message={} details={}",
                runId, level, login, sessionId, message, details);

        Net_ClientDebugLog_Response resp = new Net_ClientDebugLog_Response();
        resp.setOp(req.getOp());
        resp.setRequestId(req.getRequestId());
        resp.setStatus(WireCodes.Status.OK);
        resp.setAccepted(true);
        resp.setServerTs(System.currentTimeMillis());
        return resp;
    }

    private static String safe(String value) {
        return value == null ? "" : value.trim();
    }
}
