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.SchoolDisableMessageRequest;
import com.sikey.wa04.common.dto.header.GenericManufacturerHeader;
import com.sikey.wa04.common.dto.message.SchoolDisableChangeNoticeMessage;
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/13
 * @Description: 上课禁用消息
 */
@Slf4j
@Service
public class SchoolDisableMessageService {

    @Resource
    private RedisMessageIdIncrementingAdapter messageIdIncrementingAdapter;

    @Resource
    private RabbitMQMessaging rabbitMQMessaging;

    @Resource
    private MessageAdapter messageAdapter;

    /**
     * 上课禁用消息
     *
     * @param schoolDisableMessageRequest 上课禁用变更消息
     * @param currentUserId               当前登录用户编码
     * @return
     */
    public void schoolDisableMessageChange(SchoolDisableMessageRequest schoolDisableMessageRequest, String currentUserId) {
        // log.info("[上课禁用消息]入参: {}", JSONUtil.toJsonPrettyStr(schoolDisableMessageRequest));
        Instant sendTime = Instant.now();
        String cid = schoolDisableMessageRequest.getCid();

        // 手表
        Message message = new Message()
                .setId(new MessageId(messageIdIncrementingAdapter.incr()))
                .setType(MessageType.SCHOOL_DISABLE_CHANGE_NOTICE_MESSAGE)
                .setContent(new SchoolDisableChangeNoticeMessage.SchoolDisableChangeNoticeContent().setId(schoolDisableMessageRequest.getId()).setCid(cid).setStatus(schoolDisableMessageRequest.getStatus()).setRepeats(schoolDisableMessageRequest.getRepeats()).setStartTime(schoolDisableMessageRequest.getStartTime()).setEndTime(schoolDisableMessageRequest.getEndTime()))
                .setGroup(false)
                .setSenderId(currentUserId)
                .setReceiverId(List.of(cid))
                .setSendTime(sendTime);
        messageAdapter.save(message);
        publish(schoolDisableMessageRequest.getHeader(), message);
    }

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

}
