package com.sikey.wa04.business.application.service.message;

import cn.hutool.json.JSONUtil;
import com.sikey.wa04.business.application.converter.MessageConverter;
import com.sikey.wa04.business.domain.adapter.MessageAdapter;
import com.sikey.wa04.business.domain.entity.message.Message;
import com.sikey.wa04.business.domain.entity.message.MessageId;
import com.sikey.wa04.business.infrastructure.adapter.RabbitMQMessaging;
import com.sikey.wa04.business.infrastructure.adapter.RedisMessageIdIncrementingAdapter;
import com.sikey.wa04.business.infrastructure.dto.request.messaging.RejectStrangerMessageRequest;
import com.sikey.wa04.common.dto.header.GenericManufacturerHeader;
import com.sikey.wa04.common.dto.message.RejectStrangerChangeNoticeMessage;
import com.sikey.wa04.common.enums.MessageType;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.time.Instant;
import java.util.List;

/**
 * @Author: nelson
 * @Date: 2025/6/16
 * @Description: 拒接陌生人消息
 */
@Slf4j
@Service
public class RejectStrangerMessageService {

    @Resource
    private RedisMessageIdIncrementingAdapter messageIdIncrementingAdapter;

    @Resource
    private RabbitMQMessaging rabbitMQMessaging;

    @Resource
    private MessageAdapter messageAdapter;

    /**
     * 拒接陌生人变更消息
     *
     * @param rejectStrangerMessageRequest 拒接陌生人变更消息
     * @param currentUserId                当前登录用户编码
     * @return
     */
    public void contactMessageChange(RejectStrangerMessageRequest rejectStrangerMessageRequest, String currentUserId) {
        log.info("[拒接陌生人变更消息]入参: {}", JSONUtil.toJsonPrettyStr(rejectStrangerMessageRequest));
        Instant sendTime = Instant.now();
        String cId = rejectStrangerMessageRequest.getCid();

        // 手表
        Message message = new Message()
                .setId(new MessageId(messageIdIncrementingAdapter.incr()))
                .setType(MessageType.REJECT_STRANGER_CHANGE_NOTICE_MESSAGE)
                .setContent(new RejectStrangerChangeNoticeMessage.RejectStrangerChangeNoticeContent().setCid(cId).setDid(rejectStrangerMessageRequest.getDid()).setStatus(rejectStrangerMessageRequest.getStatus()))
                .setGroup(false)
                .setSenderId(currentUserId)
                .setReceiverId(List.of(cId))
                .setSendTime(sendTime);
        messageAdapter.save(message);
        publish(rejectStrangerMessageRequest.getHeader(), message);
    }

    private void publish(GenericManufacturerHeader headers, Message message) {
        log.info("Send message {}", message);
        Object messagingObject = MessageConverter.toMessaging(message);
        rabbitMQMessaging.publish(headers, messagingObject);
    }
}
