package de.assecutor.votianlt.messaging.plugin;

import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;

/**
 * Represents a message received from a messaging plugin.
 */
@Data
@Builder
@NoArgsConstructor
@AllArgsConstructor
public class ReceivedMessage {

    /**
     * Topic/channel the message was received on
     */
    private String topic;

    /**
     * Message payload
     */
    private byte[] payload;

    /**
     * Quality of Service level (if applicable)
     */
    private int qos;

    /**
     * Whether the message was retained
     */
    private boolean retained;

    /**
     * Timestamp when message was received
     */
    @Builder.Default
    private LocalDateTime receivedAt = LocalDateTime.now();

    /**
     * Additional metadata from the transport
     */
    @Builder.Default
    private Map<String, Object> metadata = new HashMap<>();

    /**
     * Get metadata value.
     *
     * @param key Metadata key
     * @return Metadata value or null
     */
    public Object getMetadata(String key) {
        return metadata.get(key);
    }

    /**
     * Set metadata value.
     *
     * @param key Metadata key
     * @param value Metadata value
     */
    public void setMetadata(String key, Object value) {
        metadata.put(key, value);
    }

    /**
     * Get payload as UTF-8 string.
     *
     * @return Payload as string
     */
    public String getPayloadAsString() {
        return payload != null ? new String(payload, java.nio.charset.StandardCharsets.UTF_8) : null;
    }
}

