package com.luojia_channel.modules.message.mq.consumer;

import cn.hutool.core.bean.BeanUtil;
import com.alibaba.fastjson.JSON;
import com.luojia_channel.modules.message.dto.MessageRequest;
import com.luojia_channel.modules.message.mq.MessageWrapper;
import com.luojia_channel.modules.message.mq.domain.NotificationMessage;
import com.luojia_channel.modules.message.server.WebSocketServer;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;

@Component
@RequiredArgsConstructor
@Slf4j
public class NotificationListener {
    public static final String EXCHANGE_NAME = "notify.exchange";
    public static final String QUEUE_NAME = "notify.queue";
    public static final String ROUTING_KEY = "notify.routing.key";

    private final WebSocketServer webSocketServer;
    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(name = QUEUE_NAME),
            exchange = @Exchange(name = EXCHANGE_NAME, type = "direct"),
            key = ROUTING_KEY
    ))
    public void handleNotification(MessageWrapper<NotificationMessage> wrapper) {
        try {
            NotificationMessage message = wrapper.getMessage();
            MessageRequest request = BeanUtil.copyProperties(message, MessageRequest.class);
            Integer messageType = message.getMessageType();
            if (messageType != null && !messageType.equals(0)) {
                webSocketServer.sendPrivateMessage(message.getSenderId(), request);
            } else {
                webSocketServer.sendSystemNotification(request);
            }
        } catch (Exception e) {
            // 记录异常日志
            log.error("处理消息时发生异常: {}", e.getMessage(), e);
            throw e;
        }
    }
}
