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

import com.red.circle.common.business.core.enums.ApprovalStatusEnum;
import com.red.circle.component.redis.service.RedisService;
import com.red.circle.framework.core.asserts.ResponseAssert;
import com.red.circle.framework.core.response.CommonErrorCode;
import com.red.circle.tool.core.date.TimestampUtils;
import com.red.circle.tool.core.sequence.IdWorkerUtils;
import com.red.circle.wallet.app.dto.cmd.UserBankCardAddCmd;
import com.red.circle.wallet.infra.database.mongo.entity.bank.UserBankCard;
import com.red.circle.wallet.infra.database.mongo.service.bank.UserBankCardService;
import com.red.circle.wallet.inner.error.BankErrorCode;
import java.util.concurrent.TimeUnit;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Component;

/**
 * 用户银行卡添加.
 *
 * @author pengshigang on 2022/12/15
 */
@Component
@RequiredArgsConstructor
public class UserBankCardAddExe {

  private final RedisService redisService;
  private final UserBankCardService userBankCardService;

  public void execute(UserBankCardAddCmd cmd) {

    ResponseAssert.isTrue(CommonErrorCode.REPEATED_SUBMISSION, redisService.setIfAbsent(
        "USER_BANK_CARD_ADD:" + cmd.requiredReqUserId(), 3, TimeUnit.SECONDS));

    ResponseAssert.isFalse(BankErrorCode.REPEAT_BANK_CARD_ERROR,
        userBankCardService.exist(cmd.requiredReqUserId(), cmd.getCardType(), cmd.getCardNo()));

    // 默认审核通过
    String status = ApprovalStatusEnum.PASS.name();
    userBankCardService.add(new UserBankCard()
        .setId(IdWorkerUtils.getId())
        .setUserId(cmd.requiredReqUserId())
        .setSysOrigin(cmd.requireReqSysOrigin())
        .setStatus(status)
        .setCardType(cmd.getCardType())
        .setPayee(cmd.getPayee())
        .setCardNo(cmd.getCardNo())
        .setCardName(cmd.getCardName())
        .setDel(Boolean.FALSE)
        .setCreateUser(cmd.requiredReqUserId())
        .setCreateTime(TimestampUtils.now())
    );
  }

}
