package com.red.circle.other.app.command.family;

import com.red.circle.framework.dto.PageResult;
import com.red.circle.other.app.dto.clientobject.family.FamilyNewsCO;
import com.red.circle.other.app.dto.cmd.family.FamilyNewsListCmd;
import com.red.circle.other.infra.database.rds.entity.family.FamilyNews;
import com.red.circle.other.infra.database.rds.service.family.FamilyNewsService;
import com.red.circle.other.infra.utils.ZonedDateTimeUtils;
import com.red.circle.tool.core.collection.CollectionUtils;

import java.util.List;

import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Component;

/**
 * 家族动态列表查询
 */
@Component
@RequiredArgsConstructor
public class FamilyNewsListExe {

  private final FamilyNewsService familyNewsService;

  public PageResult<FamilyNewsCO> execute(FamilyNewsListCmd cmd) {
    List<FamilyNews> newsList = familyNewsService.listByFamilyId(
            cmd.getFamilyId(),
        100
    );

    if (CollectionUtils.isEmpty(newsList)) {
      return PageResult.newPageResult(0);
    }

    int pageNo = cmd.getCursor();
    int pageSize = cmd.getLimit();
    int fromIndex = (pageNo - 1) * pageSize;
    int toIndex = Math.min(fromIndex + pageSize, newsList.size());

    PageResult<FamilyNewsCO> pageResult = PageResult.newPageResult(fromIndex, toIndex, newsList.size());

    if (fromIndex >= newsList.size()) {
      return pageResult;
    }

    List<FamilyNewsCO> resultList = newsList.subList(fromIndex, toIndex).stream()
        .map(this::convertToCO)
        .toList();

    pageResult.setRecords(resultList);
    return pageResult;
  }

  private FamilyNewsCO convertToCO(FamilyNews news) {
    return new FamilyNewsCO()
        .setId(news.getId())
        .setNewsType(news.getNewsType())
        .setOperatorId(news.getOperatorId())
        .setOperatorName(news.getOperatorName())
        .setTargetUserId(news.getTargetUserId())
        .setTargetUserName(news.getTargetUserName())
        .setContent(news.getContent())
        .setCreateTime(ZonedDateTimeUtils.toTimestamp(news.getCreateTime()));
  }
}
