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.PropsRoomLockService;
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;

/**
 * 购买房间锁.
 *
 * @author pengliang on 2021/6/3
 */
@Component
@RequiredArgsConstructor
public class PropsPurchasingRoomLockCmdExe {

  private final WalletGoldClient walletGoldClient;
  private final PropsRoomLockService propsRoomLockService;
  private final EnumConfigCacheService enumConfigCacheService;

  public BigDecimal execute(AppExtCommand cmd) {

    BigDecimal roomLockAmount = enumConfigCacheService.getValueBigDecimal(
        EnumConfigKey.ROOM_LOCK_AMOUNT, cmd.requireReqSysOrigin());

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

    // 扣款
    WalletReceiptResDTO res = ResponseAssert.requiredSuccess(
        walletGoldClient.changeBalance(GoldReceiptCmd.builder()
            .appExpenditure()
            .userId(cmd.requiredReqUserId())
            .eventId("ROOM_LOCK")
            .sysOrigin(cmd.requireReqSysOrigin())
            .origin(GoldOrigin.PURCHASE_ROOM_LOCK)
            .amount(roomLockAmount)
            .build())
    );

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