package org.dromara.main.controller;

import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.dromara.main.domain.bo.CsMessageBo;
import org.dromara.main.domain.vo.CsMessageVo;
import org.dromara.main.service.ICsMessageService;
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;

@Slf4j
@RequiredArgsConstructor
@Controller
public class ChatWebSocketController {

    private final ICsMessageService messageService;
    private final SimpMessagingTemplate messagingTemplate;

    /**
     * 处理客户端发送的文本消息
     * 前端发送到：/app/chat/send
     *
     * @param message 消息对象
     */
    @MessageMapping("/chat/send")
    public void handleChatMessage(@Payload CsMessageBo message) {
        try {
            log.info("收到WebSocket消息: sessionId={}, content={}",
                message.getSessionId(), message.getContent());

            // 保存消息到数据库
            CsMessageVo savedMessage = messageService.sendTextMessage(message);

            // 推送消息到会话频道（所有订阅该会话的用户都能收到）
            String destination = "/topic/session/" + savedMessage.getSessionId();
            messagingTemplate.convertAndSend(destination, savedMessage);

            log.info("消息已发送到会话: sessionId={}, msgId={}",
                savedMessage.getSessionId(), savedMessage.getId());
        } catch (Exception e) {
            log.error("处理聊天消息失败", e);
        }
    }

    /**
     * 发送系统通知给指定用户
     *
     * @param userId 用户ID
     * @param notification 通知内容
     */
    public void sendNotifyToUser(Long userId, Object notification) {
        try {
            messagingTemplate.convertAndSendToUser(
                userId.toString(),
                "/queue/notify",
                notification
            );
            log.info("通知已发送给用户: userId={}", userId);
        } catch (Exception e) {
            log.error("发送用户通知失败: userId={}", userId, e);
        }
    }
}
