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

import com.jeesharp.business.modules.food.entity.FoodBookingOrder;
import com.jeesharp.business.modules.food.entity.FoodPackage;
import com.jeesharp.business.modules.food.service.FoodBookingOrderService;
import com.jeesharp.business.modules.food.service.FoodPackageService;
import com.jeesharp.business.modules.trade.entity.TradeOrder;
import com.jeesharp.business.modules.trade.enums.TradeBizTypeEnum;
import com.jeesharp.business.modules.trade.enums.TradeOrderStatusEnum;
import com.jeesharp.business.modules.trade.api.TradeOrderFacadeApi;
import lombok.AllArgsConstructor;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;

/**
 * 美食预订单与统一交易订单影子核对（供定时任务或运维调用）。
 *
 * @author jeesharp
 * @since 2026-05-08
 */
@Service
@AllArgsConstructor
public class FoodTradeOrderShadowService {

    private final FoodBookingOrderService foodBookingOrderService;
    private final TradeOrderFacadeApi tradeOrderFacadeApi;
    private final FoodPackageService foodPackageService;

    /**
     * @return {@code null} 表示一致；否则返回差异说明
     */
    public String verifyFoodVsTrade(String foodOrderId) {
        FoodBookingOrder food = foodBookingOrderService.get(foodOrderId);
        if (food == null) {
            return "美食预订单不存在";
        }
        if (food.getUnifiedOrderId() == null || food.getUnifiedOrderId().isBlank()) {
            return null;
        }
        TradeOrder trade = tradeOrderFacadeApi.get(food.getUnifiedOrderId());
        if (trade == null) {
            return "统一单不存在 unifiedOrderId=" + food.getUnifiedOrderId();
        }
        if (!TradeBizTypeEnum.FOOD.getValue().equals(trade.getBizType())) {
            return "统一单 biz_type 不一致 expect=FOOD actual=" + trade.getBizType();
        }
        if (!TradeOrderStatusEnum.PAID.getValue().equals(trade.getStatus())) {
            return "统一单状态非已支付";
        }
        if (food.getMemberId() != null && trade.getMemberId() != null && !food.getMemberId().equals(trade.getMemberId())) {
            return "会员ID不一致";
        }
        if (trade.getVerticalOrderId() != null && !trade.getVerticalOrderId().equals(food.getId())) {
            return "vertical_order_id 与美食单ID不一致";
        }
        FoodPackage pkg = foodPackageService.get(food.getPackageId());
        if (pkg != null && pkg.getPrice() != null) {
            BigDecimal expect = pkg.getPrice().multiply(BigDecimal.valueOf(food.getQuantity()));
            if (trade.getPayAmount() != null && expect.compareTo(trade.getPayAmount()) != 0) {
                return "金额不一致 期望=" + expect + " 统一单实付=" + trade.getPayAmount();
            }
        }
        return null;
    }
}
