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

import cn.hutool.core.util.StrUtil;
import com.jeesharp.business.modules.coupon.api.CouponCheckoutApi;
import com.jeesharp.business.modules.trade.api.TradeOrderFacadeApi;
import lombok.AllArgsConstructor;
import org.springframework.stereotype.Component;

/**
 * 预约/订单退款 SUCCESS 后的通用收尾：退券 + 关闭统一交易单（各业态 Coordinator 复用）。
 *
 * @author jeesharp
 * @since 2026-07-03
 */
@Component
@AllArgsConstructor
public class BookingRefundTailSupport {

    private final CouponCheckoutApi couponCheckoutApi;
    private final TradeOrderFacadeApi tradeOrderFacadeApi;

    /**
     * 幂等退券（调用前须已完成各业态库存/状态写回）。
     */
    public void returnCoupon(String verticalOrderId, String refundReason, String defaultReason) {
        if (StrUtil.isBlank(verticalOrderId)) {
            return;
        }
        couponCheckoutApi.returnOnRefund(
                verticalOrderId.trim(),
                StrUtil.blankToDefault(refundReason, defaultReason));
    }

    /**
     * 幂等退券并取消统一单（调用前须已完成各业态库存/状态写回）。
     */
    public void returnCouponAndCancelUnified(
            String verticalOrderId, String unifiedOrderId, String refundReason, String defaultReason) {
        returnCoupon(verticalOrderId, refundReason, defaultReason);
        cancelUnifiedIfPresent(unifiedOrderId);
    }

    /**
     * 幂等取消统一交易单（无退券场景由各业态 Coordinator 复用）。
     */
    public void cancelUnifiedIfPresent(String unifiedOrderId) {
        if (StrUtil.isNotBlank(unifiedOrderId)) {
            tradeOrderFacadeApi.markCancelled(unifiedOrderId.trim());
        }
    }
}
