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

import com.red.circle.external.inner.endpoint.message.ImGroupClient;
import com.red.circle.external.inner.model.cmd.message.DismissGroupCmd;
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.FamilyGroupChatQueryCmd;
import com.red.circle.other.infra.database.rds.entity.family.FamilyBaseInfo;
import com.red.circle.other.infra.database.rds.entity.family.FamilyMemberInfo;
import com.red.circle.other.infra.database.rds.service.family.FamilyBaseInfoService;
import com.red.circle.other.infra.database.rds.service.family.FamilyGroupChatPayRecordService;
import com.red.circle.other.infra.database.rds.service.family.FamilyMemberInfoService;
import com.red.circle.other.infra.enums.family.FamilyRoleEnum;
import com.red.circle.other.infra.enums.family.FamilyStatusEnum;
import com.red.circle.other.inner.asserts.FamilyErrorCode;
import java.util.Objects;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

/**
 * 解散-家族群聊
 *
 * @author zongpubin on 2023/12/21
 */
@Slf4j
@Component
@AllArgsConstructor
public class FamilyDismissGroupChatExe {


  private final ImGroupClient imGroupClient;
  private final FamilyBaseInfoService familyBaseInfoService;
  private final FamilyMemberInfoService familyMemberInfoService;
  private final FamilyGroupChatPayRecordService familyGroupChatPayRecordService;

  public void execute(FamilyGroupChatQueryCmd cmd) {

    ResponseAssert.isTrue(CommonErrorCode.NO_SUITABLE_CONTENT,
        familyGroupChatPayRecordService.getByFamilyIdId(cmd.getFamilyId()));

    FamilyBaseInfo familyBaseInfo = familyBaseInfoService.getBaseInfoById(cmd.getFamilyId());
    ResponseAssert.notNull(CommonErrorCode.NOT_FOUND_RECORD_INFO, familyBaseInfo);
    ResponseAssert.isTrue(CommonErrorCode.NOT_FOUND_RECORD_INFO, Objects
        .equals(FamilyStatusEnum.NORMAL.name(), familyBaseInfo.getFamilyStatus()));

    FamilyMemberInfo familyMember = familyMemberInfoService.getFamilyMemberByUserId(
        cmd.getReqUserId());
    ResponseAssert.notNull(FamilyErrorCode.NOT_EXIST_FAMILY_INFO_DATA, familyMember);
    ResponseAssert.isTrue(FamilyErrorCode.NOT_EXIST_FAMILY_INFO_DATA,
        Objects.equals(familyMember.getFamilyId(), cmd.getFamilyId()));
    ResponseAssert.isTrue(CommonErrorCode.INSUFFICIENT_PERMISSION,
        Objects.equals(familyMember.getMemberRole(), FamilyRoleEnum.ADMIN.getKey()));

    String groupId = "FAMILY_" + familyBaseInfo.getFamilyAccount();
    DismissGroupCmd dismissGroupCmd = new DismissGroupCmd();
    dismissGroupCmd.setGroupId(groupId);
    imGroupClient.destroyGroup(dismissGroupCmd);
    familyGroupChatPayRecordService.dismissGroupByFamilyId(cmd.getFamilyId());
    
  }

}