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

import com.google.common.collect.Lists;
import com.red.circle.common.business.dto.cmd.AppExtCommand;
import com.red.circle.framework.core.asserts.ResponseAssert;
import com.red.circle.framework.core.response.CommonErrorCode;
import com.red.circle.other.app.convertor.user.UserProfileAppConvertor;
import com.red.circle.other.app.dto.clientobject.team.TeamOwnMemberCO;
import com.red.circle.other.domain.gateway.user.UserProfileGateway;
import com.red.circle.other.infra.database.mongo.entity.team.team.TeamMember;
import com.red.circle.other.infra.database.mongo.service.team.team.TeamMemberService;
import com.red.circle.other.inner.model.dto.user.UserProfileDTO;
import com.red.circle.other.inner.enums.team.TeamMemberRole;
import com.red.circle.tool.core.collection.CollectionUtils;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Component;

/**
 * 团长获取，名下成员列表.
 *
 * @author pengliang on 2023/9/25
 */
@Component
@RequiredArgsConstructor
public class TeamOwnMemberListQryExe {

  private final TeamMemberService teamMemberService;
  private final UserProfileGateway userProfileGateway;
  private final UserProfileAppConvertor userProfileAppConvertor;

  public List<TeamOwnMemberCO> execute(AppExtCommand cmd) {

    TeamMember teamMember = teamMemberService.getByMemberId(cmd.requiredReqUserId());

    ResponseAssert.isTrue(CommonErrorCode.INSUFFICIENT_PERMISSION,
        Objects.nonNull(teamMember) && TeamMemberRole.OWN.eq(teamMember.getRole()));

    List<TeamMember> teamMembers = teamMemberService.listTeamMember(teamMember.getTeamId(),
        3000);

    if (CollectionUtils.isEmpty(teamMembers)) {
      return Lists.newArrayList();
    }

    Map<Long, UserProfileDTO> userProfileMap = userProfileAppConvertor.toMapUserProfileDTO(
        userProfileGateway.mapByUserIds(teamMembers.stream().map(TeamMember::getMemberId)
            .collect(Collectors.toSet())));

    return teamMembers.stream().map(member -> new TeamOwnMemberCO()
        .setId(teamMember.getSortId())
        .setUserProfile(userProfileMap.get(teamMember.getMemberId()))
        .setRole(Objects.toString(teamMember.getRole()))
        .setCreateTime(teamMember.getCreateTime())
    ).collect(Collectors.toList());
  }

}
