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

import com.google.common.collect.Lists;
import com.red.circle.common.business.dto.cmd.AppExtCommand;
import com.red.circle.other.app.dto.clientobject.gift.PremiumGiftWallCO;
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.cache.service.other.GiftCacheService;
import com.red.circle.other.infra.database.mongo.entity.gift.PremiumGiftWallMongo;
import com.red.circle.other.infra.database.mongo.service.gift.PremiumGiftWallMongoService;
import com.red.circle.other.inner.model.dto.material.GiftConfigDTO;
import com.red.circle.tool.core.collection.CollectionUtils;
import java.util.List;
import java.util.Objects;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

/**
 * 高价值公共礼物墙.
 *
 * @author pengshigang on 2022/8/10
 */
@Slf4j
@Component
@RequiredArgsConstructor
public class PremiumGiftWallListQryExe {

  private final GiftCacheService giftCacheService;
  private final UserProfileGateway userProfileGateway;
  private final PremiumGiftWallMongoService premiumGiftWallMongoService;

  public List<PremiumGiftWallCO> execute(AppExtCommand cmd) {
    List<PremiumGiftWallMongo> giftWalls = premiumGiftWallMongoService
        .giftWalls(cmd.requireReqSysOrigin(), 50);

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

    return giftWalls.stream().map(gift -> {

          GiftConfigDTO configCache = giftCacheService.getById(gift.getGiftId());
          if (Objects.isNull(configCache)) {
            return null;
          }
          UserProfile acceptUser = userProfileGateway.getByUserId(gift.getAcceptUserId());
          if (Objects.isNull(acceptUser)) {
            return null;
          }
          UserProfile sendUser = userProfileGateway.getByUserId(gift.getSendUserId());
          if (Objects.isNull(sendUser)) {
            return null;
          }

          return new PremiumGiftWallCO()
              .setId(gift.getId())
              .setAcceptUserId(acceptUser.getId())
              .setAcceptUserName(acceptUser.getUserNickname())
              .setAcceptUserAvatar(acceptUser.getUserAvatar())
              .setSendUserId(sendUser.getId())
              .setSendUserName(sendUser.getUserNickname())
              .setSendUserAvatar(sendUser.getUserAvatar())
              .setQuantity(gift.getQuantity())
              .setGiftPhoto(configCache.getGiftPhoto())
              .setCreateTime(gift.getCreateTime());
        }).filter(Objects::nonNull)
        .toList();


  }
}
