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


import com.red.circle.other.app.dto.clientobject.user.user.UserImCountMessageCO;
import com.red.circle.other.app.dto.cmd.user.user.UserImCountCmd;
import com.red.circle.other.infra.database.rds.entity.user.user.ImCount;
import com.red.circle.other.infra.database.rds.service.user.user.ImCountService;
import java.util.Objects;
import lombok.AllArgsConstructor;
import org.springframework.stereotype.Component;

/**
 * 用户发送IM统计
 *
 * @author zongpubin on 2023/11/16
 */
@Component
@AllArgsConstructor
public class UserImCountCmdExe {

  private final ImCountService imCountService;

  public UserImCountMessageCO execute(UserImCountCmd cmd) {

    // 当前登录用户发送im统计信息
    ImCount myImCount = imCountService.getByUserIds(cmd.getReqUserId(), cmd.getAcceptUserId(),
        cmd.getReqSysOrigin().getOrigin());

    //  接收信息用户，发送im统计信息
    ImCount acceptUserImCount = imCountService.getByUserIds(cmd.getAcceptUserId(),
        cmd.getReqUserId(),
        cmd.getReqSysOrigin().getOrigin());

    if (Objects.isNull(myImCount)) {
      imCountService.save(ImCount.builder()
          .userId(cmd.getReqUserId())
          .acceptUserId(cmd.getAcceptUserId())
          .sysOrigin(cmd.getReqSysOrigin().getOrigin())
          .messageCount(1L)
          .build());

      return UserImCountMessageCO.builder()
          .acceptUserId(cmd.getAcceptUserId())
          .userId(cmd.getReqUserId())
          .messageCount(0L)
          .build();
    }

    Long messageCount = myImCount.getMessageCount() + 1L;

    imCountService.updateSelectiveById(ImCount.builder()
        .id(myImCount.getId())
        .messageCount(messageCount)
        .build());

    if (Objects.isNull(acceptUserImCount)) {

      return UserImCountMessageCO.builder()
          .acceptUserId(cmd.getAcceptUserId())
          .userId(cmd.getReqUserId())
          .messageCount(0L)
          .build();
    }

    return UserImCountMessageCO.builder()
        .acceptUserId(cmd.getAcceptUserId())
        .userId(cmd.getReqUserId())
        .messageCount(messageCount >= acceptUserImCount.getMessageCount()
            ? acceptUserImCount.getMessageCount() : messageCount)
        .build();


  }
}
