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

import com.red.circle.common.business.dto.cmd.AppExtCommand;
import com.red.circle.framework.core.asserts.ResponseAssert;
import com.red.circle.other.inner.endpoint.user.user.UserProfileClient;
import com.red.circle.wallet.app.dto.clientobject.FreightAccountCO;
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 com.red.circle.wallet.inner.error.FreightErrorCode;
import java.math.RoundingMode;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

/**
 * 获取货运代理账户信息
 *
 * @author zongpubin on 2023/7/18
 */
@Service
@RequiredArgsConstructor
public class UserFreightAccountQryExe {

  private final UserProfileClient userProfileClient;
  private final FreightSellerService freightSellerService;
  private final FreightBalanceService freightBalanceService;

  public FreightAccountCO execute(AppExtCommand cmd) {

    FreightSeller freightSeller = freightSellerService.getFreightSellerByUserId(
        cmd.requiredReqUserId());
    ResponseAssert.notNull(FreightErrorCode.NOT_SELLER, freightSeller);

    FreightBalance freightBalance = freightBalanceService.getById(freightSeller.getFreightId());

    ResponseAssert.notNull(FreightErrorCode.NOT_FREIGHT, freightBalance);
    return new FreightAccountCO()
        .setFreightBalance(freightBalanceService
            .getAvailableBalance(freightBalance.getUserId()))
        .setEarnGold(freightSeller.getEarnGold())
        .setBalance(freightSeller.getEarnGold().subtract(freightSeller.getConsumptionGold())
            .setScale(2, RoundingMode.DOWN))
        .setUserProfile(ResponseAssert.requiredSuccess(
            userProfileClient.getByUserId(freightBalance.getUserId())
        ));
  }
}
