package com.red.circle.other.app.command.room;

import com.red.circle.framework.core.asserts.ResponseAssert;
import com.red.circle.framework.core.response.CommonErrorCode;
import com.red.circle.mq.business.model.event.task.TaskApprovalEvent;
import com.red.circle.mq.rocket.business.producer.TaskMqMessage;
import com.red.circle.other.app.dto.cmd.room.RoomSubscriptionCmd;
import com.red.circle.other.infra.database.mongo.service.live.RoomProfileManagerService;
import com.red.circle.other.infra.database.rds.service.live.RoomSubscriptionCountService;
import com.red.circle.other.infra.database.rds.service.live.RoomSubscriptionService;
import com.red.circle.tool.core.date.LocalDateTimeUtils;
import com.red.circle.tool.core.text.StringUtils;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

/**
 * 房间订阅
 *
 * @author houyong on 2020/12/3
 */
@Slf4j
@Component
@RequiredArgsConstructor
public class RoomSubscriptionCmdExe {

  private final RoomSubscriptionService roomSubscriptionService;
  private final RoomProfileManagerService roomProfileManagerService;
  private final RoomSubscriptionCountService roomSubscriptionCountService;
  private final TaskMqMessage taskMqMessage;

  public Boolean execute(RoomSubscriptionCmd cmd) {
    // 无法操作，错误归属
    ResponseAssert.isTrue(CommonErrorCode.INOPERABLE_WRONG_ATTRIBUTION,
        StringUtils
            .startsWith(
                roomProfileManagerService.getRoomSysOrigin(cmd.getRoomId()),
                cmd.requireReqSysOrigin()));

    if (roomSubscriptionService.validFollow(cmd.requiredReqUserId(), cmd.getRoomId())) {
      roomSubscriptionService.remove(cmd.requiredReqUserId(), cmd.getRoomId());
      roomSubscriptionCountService.saveRoomSubscriptionCount(cmd.getRoomId(), Boolean.FALSE);
      return Boolean.FALSE;
    }
    roomSubscriptionService.add(cmd.requiredReqUserId(), cmd.getRoomId());
    roomSubscriptionCountService.saveRoomSubscriptionCount(cmd.getRoomId(), Boolean.TRUE);

    //关注一个房间任务
    taskMqMessage.sendTask(TaskApprovalEvent.builder()
        .taskId(10)
        .userId(cmd.requiredReqUserId())
        .day(LocalDateTimeUtils.nowFormat("yyyy-MM-dd"))
        .build());
    return Boolean.TRUE;
  }
}
