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

import com.red.circle.external.inner.endpoint.message.NewsletterClient;
import com.red.circle.external.inner.model.cmd.message.NewsletterResultCmd;
import com.red.circle.external.inner.model.enums.message.NewsletterEvent;
import com.red.circle.framework.core.asserts.ResponseAssert;
import com.red.circle.other.app.dto.cmd.user.user.RemoveNotActionUserCmd;
import com.red.circle.other.domain.gateway.user.UserProfileGateway;
import com.red.circle.other.domain.model.user.UserProfile;
import com.red.circle.other.infra.database.mongo.entity.live.RoomProfile;
import com.red.circle.other.infra.database.mongo.service.live.RoomProfileManagerService;
import com.red.circle.other.infra.database.rds.entity.user.user.NotActionLog;
import com.red.circle.other.infra.database.rds.service.user.user.NotActionLogService;
import com.red.circle.other.inner.asserts.RoomErrorCode;
import com.red.circle.tool.core.sequence.IdWorkerUtils;
import com.red.circle.other.inner.asserts.user.UserErrorCode;
import java.util.List;
import java.util.Map;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Component;

/**
 * 记录房间内不活跃用户
 *
 * @author zongpubin on 2023/9/6
 */
@Component
@RequiredArgsConstructor
public class UserNotActiveLogAddExe {

  private final NewsletterClient newsletterClient;
  private final UserProfileGateway userProfileGateway;
  private final NotActionLogService notActionLogService;
  private final RoomProfileManagerService roomProfileManagerService;

  public void execute(RemoveNotActionUserCmd cmd) {

    UserProfile userProfile = userProfileGateway.getByUserId(cmd.requiredReqUserId());
    ResponseAssert.notNull(UserErrorCode.USER_INFO_NOT_FOUND, userProfile);

    RoomProfile beBlackRoomProfile = roomProfileManagerService.getProfileById(cmd.getRoomId());
    ResponseAssert.notNull(RoomErrorCode.ROOM_NOT_EXISTS, beBlackRoomProfile);
    // 发送消息
    newsletterClient.send(
        new NewsletterResultCmd()
            .setUserIds(List.of(userProfile.getId()))
            .setEvent(NewsletterEvent.SYS_REMOVE_ROOM_USER)
            .setData(Map.of("userId", userProfile.getId(), "roomId", beBlackRoomProfile.getId()))
    );

    // 记录日志
    notActionLogService.save(new NotActionLog()
        .setId(IdWorkerUtils.getId())
        .setDuration(cmd.getDuration())
        .setRoomId(cmd.getRoomId())
        .setUserType(cmd.getUserType())
        .setUserId(cmd.requiredReqUserId())
        .setSysOrigin(cmd.requireReqSysOrigin())
    );
  }
}
