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

import com.red.circle.common.business.core.enums.SysOriginPlatformEnum;
import com.red.circle.common.business.dto.cmd.app.AppFlowCmd;
import com.red.circle.tool.core.collection.CollectionUtils;
import com.red.circle.other.app.convertor.user.UserProfileAppConvertor;
import com.red.circle.other.domain.model.user.UserProfile;
import com.red.circle.other.domain.gateway.user.UserProfileGateway;
import com.red.circle.other.infra.database.rds.service.user.user.InviteUserRegisterService;
import com.red.circle.other.inner.model.dto.user.UserProfileDTO;
import java.util.Comparator;
import java.util.HashSet;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Component;

/**
 * 查询邀请用户列表.
 *
 * @author pengliang on 2021/5/26
 */
@Component
@RequiredArgsConstructor
public class UserInviteUserRegisterQryExe {

  private final UserProfileGateway userProfileGateway;
  private final UserProfileAppConvertor userProfileAppConvertor;
  private final InviteUserRegisterService inviteUserRegisterService;

  public List<UserProfileDTO> execute(AppFlowCmd cmd) {
    List<Long> baseInfos = inviteUserRegisterService.listInviteRecord(
        SysOriginPlatformEnum.valueOf(cmd.requireReqSysOrigin()),
        cmd.requiredReqUserId(),
        cmd.getLastId());

    if (CollectionUtils.isEmpty(baseInfos)) {
      return CollectionUtils.newArrayList();
    }

    List<UserProfile> userProfiles = Optional.ofNullable(
            userProfileGateway.listByUserIds(new HashSet<>(baseInfos)))
        .map(profiles -> profiles.stream()
            .sorted(Comparator.comparing(UserProfile::getId, Comparator.reverseOrder()))
            .collect(Collectors.toList()))
        .orElseGet(CollectionUtils::newArrayList);

    if (CollectionUtils.isEmpty(userProfiles)) {
      return CollectionUtils.newArrayList();
    }

    return userProfileAppConvertor.toListUserProfileDTO(userProfiles);

  }

}
