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

import com.google.common.collect.Lists;
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.UserInviteAppConvertor;
import com.red.circle.other.app.convertor.user.UserProfileAppConvertor;
import com.red.circle.other.app.dto.clientobject.user.user.InviteUserRewardRecordCO;
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.entity.user.user.InviteUserRewardRecord;
import com.red.circle.other.infra.database.rds.service.user.user.InviteUserRewardRecordService;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Component;

/**
 * 用户邀请奖励记录 业务实现.
 *
 * @author Chowking on 2021/5/8
 * @since pengliang on 2021/5/26
 */
@Component
@RequiredArgsConstructor
public class UserInviteRewardRecordQryExe {

  private final UserProfileGateway userProfileGateway;
  private final UserInviteAppConvertor userInviteAppConvertor;
  private final UserProfileAppConvertor userProfileAppConvertor;
  private final InviteUserRewardRecordService inviteUserRewardRecordService;

  public List<InviteUserRewardRecordCO> execute(AppFlowCmd cmd) {
    List<InviteUserRewardRecord> inviteUserRewardRecords = inviteUserRewardRecordService
        .listInviteRewardRecord(cmd.requiredReqUserId(), cmd.getLastId());
    if (CollectionUtils.isEmpty(inviteUserRewardRecords)) {
      return Lists.newArrayList();
    }

    Map<Long, UserProfile> baseInfoMap = userProfileGateway.mapByUserIds(
        inviteUserRewardRecords.stream().map(InviteUserRewardRecord::getInviteUserId).collect(
            Collectors.toSet()));

    return inviteUserRewardRecords.stream().map(inviteUserRewardRecord -> {
          InviteUserRewardRecordCO rewardRecord = userInviteAppConvertor
              .toInviteUserRewardRecordCO(inviteUserRewardRecord);
          rewardRecord.setAmount(inviteUserRewardRecord.getQuantity());
          rewardRecord.setInviteUserProfile(
              userProfileAppConvertor.toUserProfileDTO(
                  baseInfoMap.get(inviteUserRewardRecord.getInviteUserId())));
          return rewardRecord;
        })
        .collect(Collectors.toList());
  }


}
