package com.zcloud.personnel.positioning.integration.kafka;

import java.nio.ByteBuffer;
import java.nio.charset.CharacterCodingException;
import java.nio.charset.CodingErrorAction;
import java.nio.charset.StandardCharsets;
import java.util.Arrays;
import java.util.Base64;

final class LocationKafkaPayloadPreview {

    private LocationKafkaPayloadPreview() {
    }

    static String render(byte[] payload, int maxBytes) {
        if (payload == null) {
            return "<null>";
        }
        int previewLength = Math.min(payload.length, Math.max(1, maxBytes));
        byte[] preview = Arrays.copyOf(payload, previewLength);
        String suffix = payload.length > previewLength
                ? " (truncated, totalBytes=" + payload.length + ")"
                : "";
        try {
            String text = StandardCharsets.UTF_8.newDecoder()
                    .onMalformedInput(CodingErrorAction.REPORT)
                    .onUnmappableCharacter(CodingErrorAction.REPORT)
                    .decode(ByteBuffer.wrap(preview))
                    .toString();
            return "utf8:" + oneLine(text) + suffix;
        } catch (CharacterCodingException ignored) {
            return "base64:" + Base64.getEncoder().encodeToString(preview) + suffix;
        }
    }

    private static String oneLine(String value) {
        return value.replace("\r", "\\r")
                .replace("\n", "\\n")
                .replace("\t", "\\t");
    }
}
