package com.cool.store.service.wallet.impl;

import com.cool.store.dao.wallet.WalletTradeDAO;
import com.cool.store.entity.wallet.WalletTradeDO;
import com.cool.store.enums.wallet.WalletTradeModuleEnum;
import com.cool.store.service.wallet.IWalletTradeResolve;
import com.cool.store.service.wallet.WalletTradeResolveFactory;
import com.cool.store.service.wallet.WalletTradeService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Objects;

/**
 * <p>
 * 钱包交易 服务实现类
 * </p>
 *
 * @author wangff
 * @since 2026/2/4
 */
@Service
@RequiredArgsConstructor
@Slf4j
public class WalletTradeServiceImpl implements WalletTradeService {
    private final WalletTradeDAO walletTradeDAO;
    private final WalletTradeResolveFactory walletTradeResolveFactory;

    @Override
    @Transactional
    @Async("generalThreadPool")
    public void tradeCallback(String storeId, String payNo, String tradeId, Integer payStatus) {
        WalletTradeDO walletTradeDO = walletTradeDAO.getByPayNo(payNo);
        if (Objects.nonNull(walletTradeDO)) {
            if (Objects.isNull(walletTradeDO.getTradeId())) {
                walletTradeDO.setTradeId(tradeId);
            }
            walletTradeDO.setPayStatus(payStatus);
            try {
                WalletTradeModuleEnum module = WalletTradeModuleEnum.getByModule(walletTradeDO.getModule());
                if (Objects.nonNull(module)) {
                    IWalletTradeResolve tradeResolve = walletTradeResolveFactory.getResolve(module);
                    tradeResolve.resolve(walletTradeDO);
                }
            } catch (Exception e) {
                log.error("钱包交易回调业务处理失败", e);
            }
            walletTradeDAO.updateByPrimaryKeySelective(walletTradeDO);
        }
    }
}
