package com.red.circle.other.infra.common.family;

import com.red.circle.other.infra.database.rds.entity.family.FamilyBaseInfo;
import com.red.circle.other.infra.database.rds.entity.family.FamilyNews;
import com.red.circle.other.infra.database.rds.service.family.FamilyBaseInfoService;
import com.red.circle.other.infra.database.rds.service.family.FamilyNewsService;
import com.red.circle.other.infra.enums.family.FamilyNewsTypeEnum;
import java.util.Objects;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

/**
 * 家族动态记录通用服务
 */
@Slf4j
@Component
@RequiredArgsConstructor
public class FamilyNewsRecorder {

  private final FamilyNewsService familyNewsService;
  private final FamilyBaseInfoService familyBaseInfoService;

  /**
   * 记录家族动态并更新家族公告
   */
  public void recordAndUpdateNotice(
      String sysOrigin,
      Long familyId,
      FamilyNewsTypeEnum newsType,
      Long operatorId,
      String operatorName,
      Long targetUserId,
      String targetUserName
  ) {
    familyNewsService.recordNews(
        sysOrigin,
        familyId,
        newsType,
        operatorId,
        operatorName,
        targetUserId,
        targetUserName
    );

//    updateFamilyNotice(familyId, newsType);
  }

  /**
   * 更新家族公告为最新动态
   */
  private void updateFamilyNotice(Long familyId, FamilyNewsTypeEnum  newsType) {
    try {
      FamilyNews latestNews = familyNewsService.getLatestNews(familyId);
      if (Objects.isNull(latestNews)) {
        return;
      }

      if (newsType == FamilyNewsTypeEnum.FAMILY_INFO_EDIT || newsType == FamilyNewsTypeEnum.FAMILY_NOTICE_EDIT) {
          return ;
      }

      familyBaseInfoService.updateSelectiveById(new FamilyBaseInfo()
          .setId(familyId)
          .setFamilyNotice(latestNews.getContent())
      );
    } catch (Exception e) {
      log.error("更新家族公告失败, familyId:{}, error:{}", familyId, e.getMessage());
    }
  }
}
