package de.assecutor.votianlt.messaging;

import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.nio.charset.StandardCharsets;

/**
 * Publishing helper to send JSON payloads to clients via WebSocket.
 */
public interface MessagingPublisher {
    void publishAsJson(String clientId, String messageType, Object payload);
}

@Component
@Slf4j
class MessagingPublisherImpl implements MessagingPublisher {

    private final WebSocketService webSocketService;
    private final ObjectMapper objectMapper;

    public MessagingPublisherImpl(WebSocketService webSocketService, ObjectMapper objectMapper) {
        this.webSocketService = webSocketService;
        this.objectMapper = objectMapper;
    }

    @Override
    public void publishAsJson(String clientId, String messageType, Object payload) {
        try {
            // Prüfen ob Client verbunden ist
            boolean isConnected = webSocketService.isClientConnected(clientId);
            log.debug("[Messaging] Publishing to {}/{} - connected: {}", clientId, messageType, isConnected);

            if (!isConnected) {
                log.warn("[Messaging] Client {} is not connected, cannot send {}", clientId, messageType);
                return;
            }

            String json = objectMapper.writeValueAsString(payload);
            byte[] data = json.getBytes(StandardCharsets.UTF_8);

            webSocketService.sendToClient(clientId, messageType, data).thenRun(() -> {
                log.debug("[Messaging] Successfully sent {}/{} to client {}", messageType, clientId);
            }).exceptionally(ex -> {
                log.error("[Messaging] Failed to deliver to {}/{}: {}", clientId, messageType, ex.getMessage(), ex);
                return null;
            });

        } catch (Exception e) {
            log.error("[Messaging] Failed to publish to {}/{}: {}", clientId, messageType, e.getMessage(), e);
        }
    }
}
