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


import com.google.common.collect.Lists;
import com.red.circle.other.app.convertor.user.CpBlessRecordConvert;
import com.red.circle.other.app.convertor.user.UserCpCabinConvertor;
import com.red.circle.other.app.dto.clientobject.user.user.CpBlessRecordCO;
import com.red.circle.other.app.dto.cmd.user.user.UserCpBlessRecordQueryCmd;
import com.red.circle.other.domain.gateway.user.UserProfileGateway;
import com.red.circle.other.domain.model.user.UserProfile;
import com.red.circle.other.infra.database.rds.entity.user.user.CpBlessRecord;
import com.red.circle.other.infra.database.rds.entity.user.user.CpRelationship;
import com.red.circle.other.infra.database.rds.service.user.user.CpBlessRecordService;
import com.red.circle.other.infra.database.rds.service.user.user.CpRelationshipService;
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.AllArgsConstructor;
import org.springframework.stereotype.Component;

/**
 * cp小屋祝福列表分页
 *
 * @author zongpubin on 2023/11/20
 */

@Component
@AllArgsConstructor
public class UserCpBlessRecordQueryExe {

  private final CpBlessRecordConvert cpBlessRecordConvert;
  private final CpBlessRecordService cpBlessRecordService;
  private final UserProfileGateway userProfileGateway;
  private final CpRelationshipService cpRelationshipService;

  public List<CpBlessRecordCO> execute(UserCpBlessRecordQueryCmd cmd) {

    CpRelationship relationship = cpRelationshipService.getByUserIdOrCpUserId(cmd.getUserId());
    if (Objects.isNull(relationship)) {
      return Lists.newArrayList();
    }

    List<CpBlessRecord> blessRecords = cpBlessRecordService.pageList(cmd.getUserId(),
        cmd.getLastId());

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

    Map<Long, UserProfile> userProfileMap = userProfileGateway.mapByUserIds(
        blessRecords.stream().map(CpBlessRecord::getSendUserId).collect(
            Collectors.toSet()));
    return blessRecords.stream().map(blessRecord -> {
      CpBlessRecordCO cpBlessRecordCO = cpBlessRecordConvert.toCpBlessRecordCO(blessRecord);
      cpBlessRecordCO.setSendUserNickname(
          userProfileMap.get(cpBlessRecordCO.getSendUserId()).getUserNickname());
      cpBlessRecordCO.setSendUserAvatar(
          userProfileMap.get(cpBlessRecordCO.getSendUserId()).getUserAvatar());
      return cpBlessRecordCO;
    }).collect(Collectors.toList());


  }
}
