package com.red.circle.wallet.app.command.bank.query;

import com.red.circle.common.business.dto.cmd.AppExtCommand;
import com.red.circle.framework.core.asserts.ResponseAssert;
import com.red.circle.framework.core.response.CommonErrorCode;
import com.red.circle.other.inner.model.dto.user.reigon.RegionConfigDTO;
import com.red.circle.other.inner.endpoint.user.region.UserRegionClient;
import com.red.circle.wallet.app.common.BankRoleCheckCommon;
import com.red.circle.wallet.app.dto.clientobject.UserBankCheckTransferCO;
import com.red.circle.wallet.infra.database.mongo.service.bank.UserBankBalanceService;

import java.math.BigDecimal;
import java.util.Objects;

import com.red.circle.wallet.infra.database.rds.entity.diamond.SalaryDiamondBalance;
import com.red.circle.wallet.infra.database.rds.service.diamond.SalaryDiamondBalanceService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Component;

/**
 * 银行卡转账检查.
 *
 * @author pengliang on 2023/2/24
 */
@Component
@RequiredArgsConstructor
public class UserBankCheckTransferQryExe {

  private final UserRegionClient userRegionClient;
  private final BankRoleCheckCommon bankRoleCheckCommon;
  private final UserBankBalanceService userBankBalanceService;
  private final SalaryDiamondBalanceService salaryDiamondBalanceService;

  public UserBankCheckTransferCO execute(AppExtCommand cmd) {

    RegionConfigDTO region = ResponseAssert.requiredSuccess(
        userRegionClient.getSysRegionConfigByUserId(cmd.requiredReqUserId())
    );
    ResponseAssert.notNull(CommonErrorCode.NOT_OPEN_ERROR, region);
    ResponseAssert.notNull(CommonErrorCode.NOT_OPEN_ERROR, region.getMetadata());
    ResponseAssert.isTrue(CommonErrorCode.NOT_OPEN_ERROR,
        Objects.equals(region.getMetadata().get("openTransfer"), "true"));

    return new UserBankCheckTransferCO()
        .setRole(bankRoleCheckCommon.getTransferRole(cmd.requiredReqUserId()))
        .setBalance(
            userBankBalanceService.getBalance(cmd.requiredReqUserId()).getAccurateBalance());
  }

  public UserBankCheckTransferCO executeDiamond(AppExtCommand cmd) {

    RegionConfigDTO region = ResponseAssert.requiredSuccess(
            userRegionClient.getSysRegionConfigByUserId(cmd.requiredReqUserId())
    );
    ResponseAssert.notNull(CommonErrorCode.NOT_OPEN_ERROR, region);
    ResponseAssert.notNull(CommonErrorCode.NOT_OPEN_ERROR, region.getDiamondMetadata());
    ResponseAssert.isTrue(CommonErrorCode.NOT_OPEN_ERROR,
            Objects.equals(region.getDiamondMetadata().get("openTransfer"), "true"));

    SalaryDiamondBalance salaryDiamondBalance = salaryDiamondBalanceService.getBalance(cmd.requiredReqUserId());
    BigDecimal balance = salaryDiamondBalance == null ? BigDecimal.ZERO : salaryDiamondBalanceService.getBalance(cmd.requiredReqUserId()).getBalance();

    return new UserBankCheckTransferCO()
            .setRole(bankRoleCheckCommon.getTransferRole(cmd.requiredReqUserId()))
            .setBalance(balance);
  }

}
