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.WristwatchStartupRequest;
import com.sikey.wa04.common.dto.header.GenericManufacturerHeader;
import com.sikey.wa04.common.dto.message.WristwatchStartupNoticeMessage;
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/17
 * @Description: 设备开关机
 */
@Slf4j
@Service
public class PowerOnOrShutdownMessageService {
    @Resource
    private RedisMessageIdIncrementingAdapter messageIdIncrementingAdapter;

    @Resource
    private RabbitMQMessaging rabbitMQMessaging;

    @Resource
    private MessageAdapter messageAdapter;

    /**
     * 设备开关机变更消息
     *
     * @param wristwatchStartupRequest 设备开关机变更消息
     * @return
     */
    public void powerOnOrShutdownMessageChange(WristwatchStartupRequest wristwatchStartupRequest) {
        log.info("[设备开关机变更消息]入参: {}", JSONUtil.toJsonPrettyStr(wristwatchStartupRequest));
        Instant sendTime = Instant.now();
        String cid = wristwatchStartupRequest.getCid();
        Long did = wristwatchStartupRequest.getDid();

        // 用户
        Message message = new Message()
                .setId(new MessageId(messageIdIncrementingAdapter.incr()))
                .setType(wristwatchStartupRequest.getType())
                .setContent(new WristwatchStartupNoticeMessage.WristwatchStartupNoticeContent().setCid(cid).setDid(did))
                .setGroup(false)
                .setSenderId(cid)
                .setReceiverId(List.of(wristwatchStartupRequest.getUserId()))
                .setSendTime(sendTime);
        messageAdapter.save(message);
        publish(wristwatchStartupRequest.getHeader(), message);
    }

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