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

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.infra.database.cache.service.other.EnumConfigCacheService;
import com.red.circle.other.infra.database.rds.service.props.PropsStealthBrowseService;
import com.red.circle.other.inner.asserts.PropsErrorCode;
import com.red.circle.other.inner.enums.config.EnumConfigKey;
import com.red.circle.tool.core.num.ArithmeticUtils;
import com.red.circle.wallet.inner.endpoint.wallet.WalletGoldClient;
import com.red.circle.wallet.inner.model.cmd.GoldReceiptCmd;
import com.red.circle.wallet.inner.model.dto.WalletReceiptResDTO;
import com.red.circle.wallet.inner.model.enums.GoldOrigin;
import java.math.BigDecimal;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Component;

/**
 * <p>
 * 隐身浏览 服务类.
 * </p>
 *
 * @author pengshigang
 * @since 2022-06-27
 */
@Component
@RequiredArgsConstructor
public class PropsPurchasingStealthBrowseCmdExe {

  private final WalletGoldClient walletGoldClient;
  private final EnumConfigCacheService enumConfigCacheService;
  private final PropsStealthBrowseService propsStealthBrowseService;

  public BigDecimal execute(AppExtCommand cmd) {

    BigDecimal stealthBrowsePropsAmount = enumConfigCacheService.getValueBigDecimal(
        EnumConfigKey.PROPS_STEALTH_BROWSE_AMOUNT,
        cmd.requireReqSysOrigin());

    // 配置错误
    ResponseAssert.isTrue(CommonErrorCode.CONFIGURATION_ERROR,
        ArithmeticUtils.gtZero(stealthBrowsePropsAmount));

    // 扣款
    WalletReceiptResDTO receiptRes = ResponseAssert.requiredSuccess(
        walletGoldClient.changeBalance(GoldReceiptCmd.builder()
            .appExpenditure()
            .userId(cmd.requiredReqUserId())
            .eventId("STEALTH_BROWSE")
            .sysOrigin(cmd.requireReqSysOrigin())
            .origin(GoldOrigin.PURCHASE_STEALTH_BROWSE_PROPS)
            .amount(stealthBrowsePropsAmount)
            .build())
    );

    // 5006 商品购买失败
    ResponseAssert.isTrue(PropsErrorCode.BUY_FALL,
        propsStealthBrowseService.saveOrUpdate(cmd.requiredReqUserId(), 30));
    return receiptRes.getBalance().getDollarAmount();
  }
}
