package shop.alien.store.service.impl;

import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import shop.alien.entity.store.MerchantPaymentOrder;
import shop.alien.entity.store.RefundRecord;
import shop.alien.store.service.MerchantPaymentOrderService;
import shop.alien.store.service.RefundRecordAsyncService;
import shop.alien.store.service.RefundRecordService;

/**
 * 退款相关异步落库：更新支付单 + 保存退款记录
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class RefundRecordAsyncServiceImpl implements RefundRecordAsyncService {

    private final MerchantPaymentOrderService merchantPaymentOrderService;
    private final RefundRecordService refundRecordService;

    @Async("taskExecutor")
    @Override
    public void completeRefundAsync(MerchantPaymentOrder paymentOrder, RefundRecord record) {
        String outTradeNo = paymentOrder != null ? paymentOrder.getOutTradeNo() : (record != null ? record.getOutTradeNo() : null);
        try {
            if (paymentOrder != null) {
                merchantPaymentOrderService.updateById(paymentOrder);
            }
            if (record != null) {
                refundRecordService.save(record);
            }
            log.debug("退款异步落库成功 outTradeNo={}", outTradeNo);
        } catch (Exception e) {
            log.error("退款异步落库失败 outTradeNo={}", outTradeNo, e);
        }
    }
}
