package com.red.circle.other.app.command.dynamic.delete;

import com.red.circle.common.business.core.enums.DynamicEventTypeEnum;
import com.red.circle.common.business.dto.cmd.IdLongCmd;
import com.red.circle.framework.core.asserts.ResponseAssert;
import com.red.circle.framework.core.response.CommonErrorCode;
import com.red.circle.mq.business.model.event.dynamic.DynamicEvent;
import com.red.circle.mq.rocket.business.producer.DynamicMqMessage;
import com.red.circle.other.infra.database.mongo.service.dynamic.DynamicPopularService;
import com.red.circle.other.infra.database.rds.entity.dynamic.DynamicContent;
import com.red.circle.other.infra.database.rds.service.approval.ApprovalDynamicContentService;
import com.red.circle.other.infra.database.rds.service.dynamic.DynamicContentService;
import com.red.circle.other.inner.asserts.DynamicErrorCode;
import com.red.circle.tool.core.sequence.IdWorkerUtils;
import java.util.Objects;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Component;

/**
 * <p>
 * 发布者删除自己的动态内容.
 * </p>
 *
 * @author pengshigang
 * @since 2022-04-11
 */
@Component
@RequiredArgsConstructor
public class DynamicContentDelCmdExe {

  private final DynamicMqMessage dynamicMqMessage;
  private final DynamicContentService dynamicContentService;
  private final DynamicPopularService dynamicPopularService;
  private final ApprovalDynamicContentService approvalDynamicContentService;

  public void execute(IdLongCmd cmd) {

    DynamicContent dynamicContent = dynamicContentService.getById(cmd.getId());
    ResponseAssert.notNull(DynamicErrorCode.CONTENT_IS_NULL, dynamicContent);
//    ResponseAssert.isTrue(CommonErrorCode.NOT_ACCEPT_REQUEST,
//        Objects.equals(dynamicContent.getCreateUser(), cmd.getReqUserId()));

    dynamicContent.setDel(Boolean.TRUE);
    dynamicContent.setUpdateUser(cmd.getReqUserId());
    dynamicContentService.updateSelectiveById(dynamicContent);

    dynamicPopularService.removeByDynamicId(dynamicContent.getId());

    //删除审批内容
    approvalDynamicContentService.deleteByDynamicId(dynamicContent.getId());
    //处理删除动态队列
    sendMessage(dynamicContent.getId());

  }

  /**
   * 处理业务
   *
   * @param contentId 动态ID
   */
  private void sendMessage(Long contentId) {
    dynamicMqMessage.sendDynamic(IdWorkerUtils.getIdStr(),
        new DynamicEvent()
            .setDynamicContentId(contentId)
            .setType(DynamicEventTypeEnum.DELETE)
    );

  }


}
