package com.red.circle.wallet.app.command.freight;

import com.red.circle.framework.core.asserts.ResponseAssert;
import com.red.circle.wallet.app.dto.cmd.FreightSellerUsableGoldCmd;
import com.red.circle.wallet.infra.database.rds.entity.freight.FreightBalance;
import com.red.circle.wallet.infra.database.rds.entity.freight.FreightSeller;
import com.red.circle.wallet.infra.database.rds.service.freight.FreightBalanceService;
import com.red.circle.wallet.infra.database.rds.service.freight.FreightSellerService;
import java.math.BigDecimal;
import java.util.Objects;

import com.red.circle.wallet.inner.error.FreightErrorCode;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

/**
 * 经销商授权卖家额度.
 *
 * @author zongpubin on 2023/7/31
 */

@Service
@RequiredArgsConstructor
public class UserFreightSellerUsableGoldCmdExe {

  private final FreightSellerService freightSellerService;

  private final FreightBalanceService freightBalanceService;

  public void execute(FreightSellerUsableGoldCmd cmd) {
    FreightBalance freightBalance  = freightBalanceService.getFreightBalance(cmd.getReqUserId());
    if (Objects.nonNull(freightBalance) && cmd.getEarnGold() != null){
      if (cmd.getEarnGold().compareTo(freightBalance.getEarnPoints().subtract(freightBalance.getConsumptionPoints())) > 0){
        ResponseAssert.failure(FreightErrorCode.NOT_MAX_SOME);
      }
    }else {
      cmd.setEarnGold(freightBalance.getEarnPoints().subtract(freightBalance.getConsumptionPoints()));
    }
    freightSellerService.updateSelectiveById(
        new FreightSeller()
            .setId(cmd.getId())
            .setEarnGold(cmd.getEarnGold())
            .setConsumptionGold(BigDecimal.ZERO)
    );
  }
}
