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

import com.red.circle.common.business.dto.cmd.app.AppUserIdCmd;
import com.red.circle.framework.core.asserts.ResponseAssert;
import com.red.circle.framework.core.response.CommonErrorCode;
import com.red.circle.other.domain.gateway.user.UserProfileGateway;
import com.red.circle.other.domain.gateway.user.ability.UserRelationsCalculatorGateway;
import com.red.circle.other.domain.model.user.ability.UserRelationsCalculator;
import com.red.circle.other.domain.model.user.ability.UserRelationsCalculator.CounterEnum;
import com.red.circle.other.infra.database.rds.entity.user.user.UserInterview;
import com.red.circle.other.infra.database.rds.service.props.PropsStealthBrowseService;
import com.red.circle.other.infra.database.rds.service.user.user.UserInterviewService;
import com.red.circle.tool.core.text.StringUtils;
import java.util.Objects;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Component;

/**
 * 用户关系访客.
 *
 * @author pengliang on 2023/8/10
 */
@Component
@RequiredArgsConstructor
public class UserSupportRelationVisitorAddCmdExe {

  private final UserProfileGateway userProfileGateway;
  private final UserInterviewService userInterviewService;
  private final PropsStealthBrowseService propsStealthBrowseService;
  private final UserRelationsCalculatorGateway userRelationsCalculatorGateway;

  public void execute(AppUserIdCmd cmd) {
    // 4044 无法操作，错误归属
    ResponseAssert.isTrue(CommonErrorCode.INOPERABLE_WRONG_ATTRIBUTION, StringUtils.startsWith(
        userProfileGateway.getSysOrigin(cmd.getUserId()),
        cmd.requireReqSysOrigin()));

    // 如果存在隐身访问道具则不添加访问记录
    if (existsPropsStealthBrowse(cmd)) {
      return;
    }

    UserInterview userInterview = getUserInterview(cmd);
    if (Objects.nonNull(userInterview)) {
      userInterviewService.updateSelectiveById(userInterview);
      return;
    }

    userInterviewService.save(new UserInterview()
        .setUserId(cmd.getReqUserId())
        .setInterviewUserId(cmd.getUserId())
    );
    userRelationsCalculatorGateway.process(
        new UserRelationsCalculator()
            .setUserId(cmd.getUserId())
            .setSubUserId(cmd.getUserId())
            .setType(CounterEnum.INTERVIEW)
            .setIncr(Boolean.TRUE)
    );
  }

  private UserInterview getUserInterview(AppUserIdCmd cmd) {
    return userInterviewService.checkExist(cmd.getReqUserId(), cmd.getUserId());
  }

  private boolean existsPropsStealthBrowse(AppUserIdCmd cmd) {
    return propsStealthBrowseService.existsNotExpire(cmd.getReqUserId());
  }
}
