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

import cn.hutool.core.util.StrUtil;
import com.jeesharp.business.modules.food.dto.FoodBookingRefundDTO;
import com.jeesharp.business.modules.food.entity.FoodBookingOrder;
import com.jeesharp.business.modules.food.service.FoodBookingOrderService;
import com.jeesharp.business.modules.food.vo.FoodBookingOrderQueryVO;
import com.jeesharp.business.modules.trade.application.support.BookingRefundTailSupport;
import lombok.AllArgsConstructor;
import org.springframework.stereotype.Component;

import java.util.List;

/**
 * 美食团购退款成功后的业务收尾：关单、退券、同步统一单（供管理端补偿与微信退款回调共用）。
 *
 * @author jeesharp
 * @since 2026-06-11
 */
@Component
@AllArgsConstructor
public class FoodBookingRefundCoordinator {

    private static final String DEFAULT_REFUND_REASON = "美食预订退款";

    private final FoodBookingOrderService foodBookingOrderService;
    private final BookingRefundTailSupport bookingRefundTailSupport;

    /**
     * 渠道退款 SUCCESS 后幂等关闭预订单并退券。
     */
    public void applyRefundSuccess(String orderId, String refundReason) {
        if (StrUtil.isBlank(orderId)) {
            return;
        }
        FoodBookingRefundDTO dto = new FoodBookingRefundDTO();
        dto.setOrderId(orderId.trim());
        dto.setRefundReason(refundReason);
        resolveVerticalOrderId(dto);
        FoodBookingOrder before = StrUtil.isNotBlank(dto.getOrderId())
                ? foodBookingOrderService.get(dto.getOrderId().trim()) : null;
        foodBookingOrderService.markRefunded(dto);
        String unifiedOrderId = before != null ? before.getUnifiedOrderId() : null;
        bookingRefundTailSupport.returnCouponAndCancelUnified(
                dto.getOrderId(),
                unifiedOrderId,
                dto.getRefundReason(),
                DEFAULT_REFUND_REASON);
    }

    private void resolveVerticalOrderId(FoodBookingRefundDTO dto) {
        if (dto == null || StrUtil.isBlank(dto.getOrderId())) {
            return;
        }
        FoodBookingOrder order = resolveBookingOrder(dto.getOrderId());
        if (order != null) {
            dto.setOrderId(order.getId());
        }
    }

    private FoodBookingOrder resolveBookingOrder(String orderId) {
        if (StrUtil.isBlank(orderId)) {
            return null;
        }
        FoodBookingOrder entity = foodBookingOrderService.get(orderId.trim());
        if (entity != null) {
            return entity;
        }
        FoodBookingOrderQueryVO byUnified = new FoodBookingOrderQueryVO();
        byUnified.setUnifiedOrderId(orderId.trim());
        List<FoodBookingOrder> list = foodBookingOrderService.findList(byUnified);
        return list == null || list.isEmpty() ? null : list.get(0);
    }
}
