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

import com.red.circle.common.business.dto.cmd.AppExtCommand;
import com.red.circle.framework.core.asserts.ResponseAssert;
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 com.red.circle.other.inner.asserts.FamilyErrorCode;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Component;

/**
 * <p>
 * 用户退出所在家族.
 * </p>
 *
 * @author pengshigang
 * @since 2021-07-21
 */
@Component
@RequiredArgsConstructor
public class FamilyUserExitExe {

  private final FamilyCommon familyCommon;
  private final FamilyMemberInfoService familyMemberInfoService;

  public void execute(AppExtCommand cmd) {

    FamilyMemberInfo familyMemberInfo = familyMemberInfoService
        .getFamilyMemberByUserId(cmd.getReqUserId());

    ResponseAssert.notNull(FamilyErrorCode.NOT_EXIST_FAMILY_INFO_DATA, familyMemberInfo);
    ResponseAssert.isFalse(FamilyErrorCode.FOUNDER_NOT_ALLOWED_EXIT_FAMILY,
        isAdmin(familyMemberInfo));

    familyCommon.removeFamilyUser(familyMemberInfo);

  }

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

}
