package com.jeesharp.business.modules.mall.application.support;

import cn.hutool.core.util.StrUtil;
import com.jeesharp.business.modules.member.api.MemberPointsOrderApi;
import com.jeesharp.business.modules.finance.paymentrecord.enums.PayRecordBizSceneEnum;
import com.jeesharp.business.modules.mall.entity.MallAfterSale;
import com.jeesharp.business.modules.mall.service.MallAfterSaleService;
import com.jeesharp.business.modules.trade.application.support.BookingRefundTailSupport;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

/**
 * 商城售后退款成功后的业务收尾：关单并退券（供微信退款回调与管理端处理共用）。
 *
 * @author jeesharp
 * @since 2026-06-11
 */
@Slf4j
@Component
@AllArgsConstructor
public class MallAfterSaleRefundCoordinator {

    /** 售后状态：退款中 */
    private static final int REFUNDING_STATUS = 3;

    private final MallAfterSaleService mallAfterSaleService;
    private final BookingRefundTailSupport bookingRefundTailSupport;
    private final MemberPointsOrderApi memberPointsOrderApi;

    /**
     * 渠道退款 SUCCESS 或管理端确认后，幂等完成售后并退回优惠券。
     */
    @Transactional(readOnly = false)
    public void applyRefundSuccess(String afterSaleId, String handlerId, String handleRemark) {
        if (StrUtil.isBlank(afterSaleId)) {
            return;
        }
        MallAfterSale before = mallAfterSaleService.get(afterSaleId.trim());
        mallAfterSaleService.handleAfterSale(afterSaleId.trim(), handlerId, handleRemark);
        if (before != null
                && REFUNDING_STATUS == before.getStatus()
                && StrUtil.isNotBlank(before.getOrderId())) {
            bookingRefundTailSupport.returnCoupon(
                    before.getOrderId(), handleRemark, "商城售后退款");
            triggerPointsOnRefund(before.getOrderId());
        }
    }

    private void triggerPointsOnRefund(String mallOrderId) {
        try {
            memberPointsOrderApi.onOrderRefunded(
                    PayRecordBizSceneEnum.MALL_ORDER.getCode(), mallOrderId.trim());
        } catch (Exception ex) {
            log.warn("商城退款积分扣回失败 mallOrderId={}", mallOrderId, ex);
        }
    }
}
