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

import com.red.circle.framework.core.asserts.ResponseAssert;
import com.red.circle.tool.core.sequence.IdWorkerUtils;
import com.red.circle.wallet.app.dto.cmd.FreightSellerCmd;
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.infra.sync.ControlSwitch;
import com.red.circle.wallet.inner.error.FreightErrorCode;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

/**
 * 新增经销商卖家
 *
 * @author zongpubin on 2023/7/17
 */
@Service
@RequiredArgsConstructor
public class UserFreightSellerAddCmdExe {

  private final ControlSwitch controlSwitch;
  private final FreightSellerService freightSellerService;
  private final FreightBalanceService freightBalanceService;

  public void execute(FreightSellerCmd cmd) {
    controlSwitch.execute(cmd.requireReqSysOriginChildEnum());

    FreightBalance freightBalance = freightBalanceService.getFreightBalance(
        cmd.requiredReqUserId());

    ResponseAssert.notNull(FreightErrorCode.NOT_FREIGHT, freightBalance);
    cmd.setFreightId(freightBalance.getId());
    // 卖家已存在
    ResponseAssert.isFalse(FreightErrorCode.USER_FREIGHT_SELLER_EXISTS,
        freightSellerService.existsSeller(cmd.getUserId()));

    // 是否为货运代理
    ResponseAssert.isFalse(FreightErrorCode.IS_FREIGHT,
        freightBalanceService.existsBalance(cmd.getUserId()));

    Integer sellerQuantity = freightBalanceService.selectSellerQuantity(cmd.getFreightId(),
        cmd.requireReqSysOrigin());

    Long count = freightSellerService.countByFreightId(cmd.getFreightId(),
        cmd.requireReqSysOrigin());
    // 经销商家卖家数量已达上限
    ResponseAssert.isFalse(FreightErrorCode.USER_FREIGHT_SELLER_LIMIT, sellerQuantity <= count);

    freightSellerService.save(new FreightSeller()
        .setFreightId(cmd.getFreightId())
        .setUserId(cmd.getUserId())
        .setSysOrigin(cmd.requireReqSysOrigin())
        .setId(IdWorkerUtils.getId())
    );
  }
}
