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

import com.red.circle.framework.core.asserts.ResponseAssert;
import com.red.circle.framework.dto.PageResult;
import com.red.circle.other.app.dto.clientobject.dynamic.DynamicLikeListCO;
import com.red.circle.other.app.dto.cmd.dynamic.DynamicLikeLimitCmd;
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.dynamic.DynamicContent;
import com.red.circle.other.infra.database.rds.entity.dynamic.DynamicLike;
import com.red.circle.other.infra.database.rds.service.dynamic.DynamicContentService;
import com.red.circle.other.infra.database.rds.service.dynamic.DynamicLikeService;
import com.red.circle.other.inner.asserts.DynamicErrorCode;
import com.red.circle.tool.core.collection.CollectionUtils;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
import java.util.stream.Collectors;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Component;

/**
 * 动态点赞列表查询.
 *
 * @author pengshigang
 * @since 2025-01-29
 */
@Component
@RequiredArgsConstructor
public class DynamicLikeQryExe {

  private final UserProfileGateway userProfileGateway;
  private final DynamicContentService dynamicContentService;
  private final DynamicLikeService dynamicLikeService;

  public PageResult<DynamicLikeListCO> execute(DynamicLikeLimitCmd cmd) {

    DynamicContent dynamicContent = dynamicContentService.getById(cmd.getDynamicId());
    ResponseAssert.notNull(DynamicErrorCode.CONTENT_IS_NULL, dynamicContent);
    ResponseAssert.isFalse(DynamicErrorCode.CONTENT_DELETE, dynamicContent.getDel());

    PageResult<DynamicLike> likes = pageData(cmd);
    if (CollectionUtils.isEmpty(likes.getRecords())) {
      return PageResult.newPageResult(0);
    }

    Map<Long, UserProfile> userMap = userProfileGateway.mapByUserIds(getUserIds(likes));

    return likes.convert(like -> {

      DynamicLikeListCO listCO = new DynamicLikeListCO();
      UserProfile createUser = userMap.get(like.getCreateUser());
      if (Objects.isNull(createUser)) {
        return null;
      }
      listCO.setUserAvatar(createUser.getUserAvatar());
      listCO.setUserNickname(createUser.getUserNickname());
      listCO.setUserSex(createUser.getUserSex());
      listCO.setAge(createUser.getAge());
      listCO.setUserId(createUser.getId());

      listCO.setId(like.getId());
      listCO.setDynamicId(like.getDynamicContentId());
      listCO.setCreateTime(like.getCreateTime());

      return listCO;

    });
  }

  private Set<Long> getUserIds(PageResult<DynamicLike> likes) {
    return likes.getRecords().stream()
        .map(DynamicLike::getCreateUser)
        .filter(Objects::nonNull)
        .collect(Collectors.toSet());
  }

  private PageResult<DynamicLike> pageData(DynamicLikeLimitCmd cmd) {
    return dynamicLikeService.pageByTimeDesc(cmd.getPageReq(), cmd.getDynamicId());
  }

}
