package dev.sonpx.loyalty.agent.service;

import dev.sonpx.loyalty.agent.domain.AgentEvent;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.messaging.simp.SimpMessagingTemplate;
import org.springframework.stereotype.Component;

@Slf4j
@Component
@RequiredArgsConstructor
public class AgentEventPublisher {

    private static final String CHAT_EVENTS_DESTINATION = "/queue/chat-events";

    private final SimpMessagingTemplate messagingTemplate;

    public void token(String sessionId, String messageId, String content) {
        send(sessionId, AgentEvent.token(messageId, content));
    }

    public void toolRunning(String sessionId, String messageId, String toolName) {
        send(sessionId, AgentEvent.toolStatus(messageId, toolName, "running"));
    }

    public void toolDone(String sessionId, String messageId, String toolName) {
        send(sessionId, AgentEvent.toolStatus(messageId, toolName, "done"));
    }

    public void done(String sessionId, String messageId) {
        send(sessionId, AgentEvent.done(messageId));
    }

    public void error(String sessionId, String messageId, String errorMessage) {
        send(sessionId, AgentEvent.error(messageId, errorMessage));
    }

    private void send(String sessionId, AgentEvent event) {
        if ("TOKEN".equals(event.type())) {
            log.trace("Publishing STOMP event type={} for session={}", event.type(), sessionId);
        } else {
            log.debug("Publishing STOMP event type={} for session={}", event.type(), sessionId);
        }
        messagingTemplate.convertAndSendToUser(sessionId, CHAT_EVENTS_DESTINATION, event);
    }
}
