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.CancelFamilyApplyCmd;
import com.red.circle.other.infra.database.rds.entity.family.FamilyMessage;
import com.red.circle.other.infra.database.rds.service.family.FamilyMessageService;
import com.red.circle.other.inner.asserts.FamilyErrorCode;
import com.red.circle.other.inner.enums.FamilyMessageStatusEnum;
import java.util.Objects;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Component;

/**
 * 取消家族申请.
 */
@Component
@RequiredArgsConstructor
public class CancelFamilyApplyExe {

  private final FamilyMessageService familyMessageService;

  public void execute(CancelFamilyApplyCmd cmd) {

    FamilyMessage msg = familyMessageService.getById(cmd.getMsgId());
    ResponseAssert.notNull(CommonErrorCode.NOT_FOUND_RECORD_INFO, msg);
    ResponseAssert.isTrue(CommonErrorCode.DATA_ERROR, 
        Objects.equals(msg.getSenderUser(), cmd.getReqUserId()));
    ResponseAssert.isFalse(FamilyErrorCode.USER_JOINED_FAMILY,
            Objects.equals(msg.getStatus(), FamilyMessageStatusEnum.APPROVED.getCode()));
    ResponseAssert.isTrue(CommonErrorCode.DATA_ERROR, 
        Objects.equals(msg.getStatus(), FamilyMessageStatusEnum.PENDING.getCode()));

    msg.setStatus(FamilyMessageStatusEnum.CANCELLED.getCode());
    msg.setUpdateUser(cmd.getReqUserId());
    familyMessageService.updateSelectiveById(msg);
  }
}
