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.other.app.dto.cmd.room.RoomMemberIdentityCmd;
import com.red.circle.other.infra.database.mongo.entity.live.RoomProfileManager;
import com.red.circle.other.infra.database.mongo.entity.sys.ApiOperationLog;
import com.red.circle.other.infra.database.mongo.service.live.RoomProfileManagerService;
import com.red.circle.other.infra.database.mongo.service.sys.ApiOperationLogService;
import com.red.circle.other.infra.database.rds.entity.live.RoomMember;
import com.red.circle.other.infra.database.rds.service.live.RoomMemberService;
import com.red.circle.other.inner.asserts.RoomErrorCode;
import com.red.circle.other.inner.enums.live.RoomUserRolesEnum;
import com.red.circle.tool.core.date.DateUtils;
import com.red.circle.tool.core.json.JacksonUtils;
import com.red.circle.tool.core.sequence.IdWorkerUtils;
import java.util.Objects;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Component;

/**
 * 加入房间邀请检测.
 *
 * @author pengliang on 2021/4/28
 */
@Component
@RequiredArgsConstructor
public class JoinRoomInviteCheckCmd {

  private final RoomMemberService roomMemberService;
  private final ApiOperationLogService apiOperationLogService;
  private final RoomProfileManagerService roomProfileManagerService;

  public Boolean execute(RoomMemberIdentityCmd cmd) {
    apiOperationLogService.add(
        new ApiOperationLog()
            .setId(IdWorkerUtils.getIdStr())
            .setRequestUserId(cmd.requiredReqUserId())
            .setApiDesc("身份变更-发出邀请")
            .setBusinessCode("ROOM_ROLES_CHANGE_INVITE")
            .setBusinessContent(Objects.toString(cmd.getRoomId()))
            .setCmd(JacksonUtils.toJson(cmd))
            .setExpiredTime(DateUtils.nowPlusDays(7))
            .setCreateTime(DateUtils.now())
    );

    // 验证操作人权限
    RoomMember requestUser = roomMemberService.getRoomMember(cmd.getRoomId(),
        cmd.requiredReqUserId());
    // 权限不足
    ResponseAssert.isTrue(CommonErrorCode.INSUFFICIENT_PERMISSION,
        Objects.nonNull(requestUser) && requestUser.checkHomeownerOrAdmin());

    RoomMember roomMember = roomMemberService.getRoomMember(cmd.getRoomId(), cmd.getChangeUserId());
    // 已加入成员列表
    ResponseAssert.isNull(RoomErrorCode.JOINED_THE_MEMBER_LIST, roomMember);

    RoomProfileManager manager = roomProfileManagerService.getById(cmd.getRoomId());

    if (Objects.equals(cmd.getUserType(), RoomUserRolesEnum.MEMBER)) {
      // 已达到成员上限
      ResponseAssert.isFalse(RoomErrorCode.ROOM_MEMBER_IS_MAX, manager.checkMemberOverflow());
      return Boolean.TRUE;
    }

    if (Objects.equals(cmd.getUserType(), RoomUserRolesEnum.ADMIN)) {
      // 管理人员数量已用完
      ResponseAssert.isFalse(RoomErrorCode.ROOM_ADMIN_OVERFLOW, manager.checkAdminOverflow());
      return Boolean.TRUE;
    }

    return Boolean.FALSE;
  }

}
