package com.red.circle.other.app.command.team.query;

import com.red.circle.framework.core.asserts.ResponseAssert;
import com.red.circle.framework.core.dto.CommonCommand;
import com.red.circle.other.app.convertor.team.TeamAppConvertor;
import com.red.circle.other.app.convertor.user.UserProfileAppConvertor;
import com.red.circle.other.app.dto.clientobject.team.TeamProfileCO;
import com.red.circle.other.app.dto.clientobject.team.TeamWaitApplyMessageCO;
import com.red.circle.other.domain.gateway.user.UserProfileGateway;
import com.red.circle.other.infra.database.mongo.entity.team.team.TeamApplicationProcess;
import com.red.circle.other.infra.database.mongo.entity.team.team.TeamMember;
import com.red.circle.other.infra.database.mongo.service.team.team.TeamApplicationProcessService;
import com.red.circle.other.infra.database.mongo.service.team.team.TeamMemberService;
import com.red.circle.other.infra.database.mongo.service.team.team.TeamProfileService;
import com.red.circle.other.inner.asserts.team.TeamErrorCode;
import java.util.Objects;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Component;

/**
 * 用户等待申请加入团队资料信息.
 *
 * @author pengliang on 2022/12/29
 */
@Component
@RequiredArgsConstructor
public class TeamProfileByUserApplyWaitQryExe {

  private final TeamAppConvertor teamAppConvertor;
  private final TeamMemberService teamMemberService;
  private final UserProfileGateway userProfileGateway;
  private final TeamProfileService teamProfileService;
  private final UserProfileAppConvertor userProfileAppConvertor;
  private final TeamApplicationProcessService teamApplicationProcessService;

  public TeamWaitApplyMessageCO execute(CommonCommand cmd) {

    TeamMember teamMember = teamMemberService.getByMemberId(cmd.getReqUserId());
    ResponseAssert.isNull(TeamErrorCode.JOINED_TEAM, teamMember);

    TeamApplicationProcess process = teamApplicationProcessService.getTeamWaitApprovalJoin(
        cmd.getReqUserId());

    if (Objects.isNull(process)) {
      return null;
    }
    TeamProfileCO co = teamAppConvertor.toTeamProfile(
        teamProfileService.getById(process.getAssociateId()));

    return new TeamWaitApplyMessageCO()
        .setMessageId(process.getId())
        .setTeamProfile(co)
        .setOwnUserProfile(
            userProfileAppConvertor.toUserProfileDTO(
                userProfileGateway.getByUserId(co.getOwnUserId())));
  }

}
