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.PropsUserAppConvertor;
import com.red.circle.other.app.convertor.user.UserProfileAppConvertor;
import com.red.circle.other.app.dto.clientobject.user.relation.UserSupportRelationCO;
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.UserSubscription;
import com.red.circle.other.infra.database.rds.service.user.user.UserSubscriptionService;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Component;

/**
 * 用户关系订阅粉丝列表
 *
 * @author pengliang on 2020/11/11
 */
@Component
@RequiredArgsConstructor
public class UserRelationFansQryExe {

  private final PropsUserAppConvertor propsUserAppConvertor;
  private final UserProfileGateway userProfileGateway;
  private final UserProfileAppConvertor userProfileAppConvertor;
  private final UserSubscriptionService userSubscriptionService;

  public List<UserSupportRelationCO> execute(AppFlowCmd cmd) {
    List<UserSubscription> userFans = userSubscriptionService
        .getBySubscriptionUserId(cmd.requiredReqUserId(), cmd.getLastId());
    if (CollectionUtils.isEmpty(userFans)) {
      return Lists.newArrayList();
    }

    Map<Long, UserProfile> userProfileMap = userProfileGateway.mapByUserIds(
        getUserIds(userFans));

    return userFans.stream().map(userSubscription -> {
          UserProfile userProfile = userProfileMap.get(userSubscription.getUserId());
          return new UserSupportRelationCO()
              .setId(userSubscription.getId())
              .setUserProfile(
                  userProfileAppConvertor.toUserProfileDTO(userProfile))
              .setMutualRelations(userSubscription.getMutualRelations())
              .setUseProps(propsUserAppConvertor.toListUsePropsDTO(userProfile.getUseProps()));
        })
        .collect(Collectors.toList());
  }


  private Set<Long> getUserIds(List<UserSubscription> userFans) {
    return userFans.stream()
        .map(UserSubscription::getUserId).collect(Collectors.toSet());
  }
}
