package com.red.circle.console.app.service.app.game;

import com.red.circle.console.app.convertor.sys.GameListConfigAppConvertor;
import com.red.circle.console.app.dto.clienobject.game.GameKtvUserSongCountCO;
import com.red.circle.framework.core.asserts.ResponseAssert;
import com.red.circle.framework.dto.PageResult;
import com.red.circle.other.inner.endpoint.game.GameKtvClient;
import com.red.circle.other.inner.model.cmd.game.GameKtvUserSongCountQryCmd;
import com.red.circle.tool.core.collection.CollectionUtils;
import com.red.circle.other.inner.model.dto.user.UserProfileDTO;
import com.red.circle.other.inner.endpoint.user.user.UserProfileClient;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

/**
 * ktv点歌记录
 *
 * @author zongpubin on 2023/5/11
 */
@Service
@RequiredArgsConstructor
public class GameKtvUserSongServiceImpl implements GameKtvUserSongService {

  private final GameKtvClient gameKtvClient;
  private final UserProfileClient userProfileClient;
  private final GameListConfigAppConvertor gameListConfigAppConvertor;


  @Override
  public PageResult<GameKtvUserSongCountCO> listUserSongCount(GameKtvUserSongCountQryCmd query) {
    PageResult<GameKtvUserSongCountCO> pageResult = ResponseAssert.requiredSuccess(
            gameKtvClient.listUserSongCount(query))
        .convert(gameListConfigAppConvertor::toGameKtvUserSongCountCO);
    Map<Long, UserProfileDTO> userProfileMap = getUserProfileMap(
        pageResult.getRecords().stream().toList());
    if (CollectionUtils.isEmpty(userProfileMap)) {
      return pageResult;
    }
    return pageResult.convert(userSongCount -> {
      UserProfileDTO userProfile = userProfileMap.get(userSongCount.getUserId());
      if (Objects.isNull(userProfile)) {
        return null;
      }
      userSongCount.setUserProfile(userProfile);
      return userSongCount;
    });
  }


  private Map<Long, UserProfileDTO> getUserProfileMap(List<GameKtvUserSongCountCO> userSongCounts) {
    return ResponseAssert.requiredSuccess(userProfileClient.mapByUserIds(
        userSongCounts.stream().map(GameKtvUserSongCountCO::getUserId)
            .collect(Collectors.toSet())));
  }

}
