package com.red.circle.wallet.infra.gateway;

import com.alibaba.nacos.shaded.com.google.common.base.Throwables;
import com.red.circle.tool.core.date.DateUtils;
import com.red.circle.tool.core.sequence.IdWorkerUtils;
import com.red.circle.wallet.domain.gateway.WalletExceptionLogGateway;
import com.red.circle.wallet.domain.wallet.WalletExceptionLogRecord;
import com.red.circle.wallet.infra.database.cache.service.WalletGoldCacheService;
import com.red.circle.wallet.infra.database.rds.entity.WalletExceptionLog;
import com.red.circle.wallet.infra.database.rds.service.WalletExceptionLogService;
import java.util.Objects;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.stereotype.Component;

/**
 * 钱包异常日志 实现.
 *
 * @author pengliang on 2023/7/2
 */
@Slf4j
@Component
@RequiredArgsConstructor
public class WalletExceptionLogGatewayImpl implements WalletExceptionLogGateway {

  private final WalletGoldCacheService walletGoldCacheService;
  private final WalletExceptionLogService walletExceptionLogService;

  @Override
  public void add(WalletExceptionLogRecord logRecord) {
    WalletExceptionLog walletExceptionLog = toWalletExceptionLog(
        logRecord);
    try {
      walletExceptionLogService.save(walletExceptionLog);
    } catch (DuplicateKeyException ignore) {
      // ignore
    } catch (Exception ex) {
      walletGoldCacheService.pushErrorLog(walletExceptionLog);
      log.error("{}", Throwables.getStackTraceAsString(ex));
    }
  }

  private WalletExceptionLog toWalletExceptionLog(WalletExceptionLogRecord logRecord) {
    WalletExceptionLog log = new WalletExceptionLog()
        .setId(IdWorkerUtils.getId())
        .setAssetRecordId(logRecord.getAssetRecordId())
        .setReceiptType(logRecord.getReceiptType().getType())
        .setUserId(logRecord.getUserId())
        .setSysOrigin(logRecord.getSysOrigin())
        .setEventType(logRecord.getEventType())
        .setEventDesc(logRecord.getEventDesc())
        .setEventId(logRecord.getEventId())
        .setRemark(logRecord.getRemark())
        .setOpUserType(logRecord.getOpUserType().getType())
        .setPennyAmount(logRecord.getPennyAmount())
        .setPennyBalance(logRecord.getPennyBalance())
        .setBizType(logRecord.getBizType().getType())
        .setReason(logRecord.getReason().name());
    log.setCreateTime(Objects.nonNull(logRecord.getCreateTime())
        ? logRecord.getCreateTime()
        : DateUtils.now());
    return log;
  }

}
