package com.red.circle.wallet.app.common;

import com.red.circle.framework.core.asserts.ResponseAssert;
import com.red.circle.other.inner.asserts.team.TeamErrorCode;
import com.red.circle.other.inner.endpoint.team.agency.AgentTeamClient;
import com.red.circle.other.inner.endpoint.team.bd.BdTeamInfoClient;
import com.red.circle.other.inner.model.dto.agency.agency.TeamMemberDTO;
import com.red.circle.other.inner.enums.team.TeamMemberRole;
import com.red.circle.tool.core.text.StringUtils;
import com.red.circle.wallet.infra.database.rds.service.freight.FreightBalanceService;
import java.util.Objects;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Component;

/**
 * @author pengliang on 2023/2/24
 */
@Component
@RequiredArgsConstructor
public class BankRoleCheckCommon {

  private final BdTeamInfoClient bdTeamClient;
  private final AgentTeamClient agentTeamClient;
  private final FreightBalanceService freightBalanceService;
  private final String BD = "BD";
  private final String TEAM_OWN = "TEAM_OWN";
  private final String TEAM_MEMBER = "TEAM_MEMBER";
  private final String FREIGHT = "FREIGHT";

  /**
   * 提现角色检查.
   */
  public String getWithdrawRole(Long userId) {
    if (ResponseAssert.requiredSuccess(bdTeamClient.check(userId))) {
      return BD;
    }
    TeamMemberDTO teamMember = ResponseAssert.requiredSuccess(
        agentTeamClient.getByMemberId(userId)
    );
    if (Objects.isNull(teamMember)) {
      return "";
    }
    return Objects.equals(teamMember.getRole(), TeamMemberRole.OWN) ? TEAM_OWN : TEAM_MEMBER;
  }

  /**
   * 转账角色检查.
   */
  public String getTransferRole(Long userId) {
    TeamMemberDTO teamMember = ResponseAssert.requiredSuccess(
        agentTeamClient.getByMemberId(userId)
    );

    if (Objects.nonNull(teamMember)) {
      return Objects.equals(teamMember.getRole(), TeamMemberRole.OWN) ? TEAM_OWN : TEAM_MEMBER;
    }

    if (ResponseAssert.requiredSuccess(bdTeamClient.check(userId))) {
      return BD;
    }

    return StringUtils.EMPTY;
  }


  /**
   * 兑换金币角色检查.
   */
  public String getExchangeGoldRole(Long userId) {
    if (freightBalanceService.existsBalance(userId)) {
      return FREIGHT;
    }

    if (ResponseAssert.requiredSuccess(bdTeamClient.check(userId))) {
      return BD;
    }
    TeamMemberDTO teamMember = ResponseAssert.requiredSuccess(
        agentTeamClient.getByMemberId(userId)
    );
    if (Objects.isNull(teamMember)) {
      return "";
    }
    return Objects.equals(teamMember.getRole(), TeamMemberRole.OWN) ? TEAM_OWN : TEAM_MEMBER;
  }

}
