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

import cn.hutool.core.util.StrUtil;
import com.jeesharp.business.modules.food.application.support.FoodBookingRefundCoordinator;
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.framework.exception.BizErrorException;
import lombok.AllArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * 餐饮预订退款成功关单用例：微信回调与管理端补偿入口，不依赖 {@code PayRefundApi}。
 *
 * @author jeesharp
 * @since 2026-06-29
 */
@Service
@AllArgsConstructor
@Transactional(readOnly = true)
public class FoodBookingRefundConfirmApplicationService {

    private final FoodBookingOrderService foodBookingOrderService;
    private final FoodBookingRefundCoordinator foodBookingRefundCoordinator;

    /**
     * 退款成功补偿/微信回调：关单并同步统一单。
     */
    @Transactional(readOnly = false)
    public void confirmBookingRefund(FoodBookingRefundDTO dto) {
        resolveVerticalOrderId(dto);
        if (dto == null || StrUtil.isBlank(dto.getOrderId())) {
            throw new BizErrorException("预订单ID不能为空");
        }
        foodBookingRefundCoordinator.applyRefundSuccess(
                dto.getOrderId().trim(),
                StrUtil.blankToDefault(dto.getRefundReason(), "美食预订退款"));
    }

    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);
    }
}
