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

import com.red.circle.framework.core.asserts.ResponseAssert;
import com.red.circle.framework.core.response.CommonErrorCode;
import com.red.circle.other.app.dto.cmd.family.FamilyRemoveUserCmd;
import com.red.circle.other.infra.common.family.FamilyCommon;
import com.red.circle.other.infra.database.rds.entity.family.FamilyMemberInfo;
import com.red.circle.other.infra.database.rds.service.family.FamilyMemberInfoService;
import java.util.Objects;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

/**
 * <p>
 * 移除家族用户.
 * </p>
 *
 * @author pengshigang
 * @since 2021-07-21
 */
@Slf4j
@Component
@RequiredArgsConstructor
public class FamilyRemoveUserExe {

  private final FamilyCommon familyCommon;
  private final FamilyMemberInfoService familyMemberInfoService;

  public void execute(FamilyRemoveUserCmd cmd) {

    FamilyMemberInfo member = getRemovedPersonMember(cmd);
    if (Objects.isNull(member)) {
      return;
    }

    Boolean isExistFamily = getExistFamilyByUserId(cmd);
    if (Boolean.FALSE.equals(isExistFamily)) {
      log.error("DELETE_FAILURE: 操作人:{} 被移除成员ID:{}", cmd.getReqUserId(),
          cmd.getRemoveMemberId());
      ResponseAssert.failure(CommonErrorCode.DELETE_FAILURE);
      return;
    }

    FamilyMemberInfo manageMember = getOperatorMember(cmd);
    if (Objects.isNull(manageMember)) {
      log.error("DELETE_FAILURE: 操作人不存在: 操作人:{} 被移除成员ID:{}",
          cmd.getReqUserId(), cmd.getRemoveMemberId());
      ResponseAssert.failure(CommonErrorCode.DELETE_FAILURE);
      return;
    }

    ResponseAssert.isFalse(CommonErrorCode.INSUFFICIENT_PERMISSION,
        Objects.equals(member.getMemberUserId(), manageMember.getMemberUserId()));

    if (isAdmin(manageMember)) {
      familyCommon.removeFamilyUser(member);
      return;
    }

    if (isAllowUpdate(manageMember, member)) {
      familyCommon.removeFamilyUser(member);
      return;
    }

    ResponseAssert.failure(CommonErrorCode.INSUFFICIENT_PERMISSION);

  }

  private Boolean getExistFamilyByUserId(FamilyRemoveUserCmd cmd) {
    return familyCommon.isExistFamilyByUserId(cmd.getReqUserId());
  }

  private boolean isAdmin(FamilyMemberInfo manageMember) {
    return familyCommon.isAdmin(manageMember.getMemberRole());
  }

  private boolean isAllowUpdate(FamilyMemberInfo manageMember, FamilyMemberInfo member) {
    return familyCommon.isManage(manageMember.getMemberRole()) && familyCommon
        .isMember(member.getMemberRole());
  }


  private FamilyMemberInfo getRemovedPersonMember(FamilyRemoveUserCmd cmd) {
    return familyMemberInfoService
        .geMemberByMemberId(cmd.getRemoveMemberId());
  }

  private FamilyMemberInfo getOperatorMember(FamilyRemoveUserCmd cmd) {
    return familyMemberInfoService.getFamilyMemberByUserId(cmd.getReqUserId());
  }


}
