package org.dromara.chat.controller;

import lombok.RequiredArgsConstructor;
import org.dromara.chat.domain.bo.ChatMessageBo;
import org.dromara.chat.service.ChatMessageService;
import org.springframework.messaging.handler.annotation.MessageMapping;
import org.springframework.messaging.handler.annotation.Payload;
import org.springframework.messaging.simp.SimpMessagingTemplate;
import org.springframework.stereotype.Controller;

import java.util.Map;

@Controller
@RequiredArgsConstructor
public class ChatStompController {
    private final SimpMessagingTemplate messagingTemplate;
    private final ChatMessageService chatMessageService;

    @MessageMapping("/chat/send")
    public void send(@Payload Map<String, Object> payload) {
        Long sessionId = toLong(payload.get("sessionId"));
        Long userId = toLong(payload.get("userId"));
        String content = String.valueOf(payload.get("content"));
        ChatMessageBo bo = new ChatMessageBo();
        bo.setSessionId(sessionId);
        bo.setUserId(userId);
        bo.setContent(content);
        bo.setRole("user");
        chatMessageService.insertByBo(bo);
        messagingTemplate.convertAndSend("/topic/session/" + sessionId, Map.of(
                "sessionId", sessionId, "userId", userId, "content", content));
    }

    private Long toLong(Object o) {
        if (o == null) return null;
        if (o instanceof Number) return ((Number) o).longValue();
        try {
            return Long.parseLong(String.valueOf(o));
        } catch (Exception e) {
            return null;
        }
    }
}
