package com.starry.admin.modules.order.service.impl;

import com.starry.admin.common.exception.CustomException;
import com.starry.admin.modules.order.module.constant.OrderConstant;
import com.starry.admin.modules.order.module.dto.OrderAmountBreakdown;
import com.starry.admin.modules.order.module.dto.OrderCreationContext;
import com.starry.admin.modules.order.module.dto.OrderPlacementCommand;
import com.starry.admin.modules.order.module.dto.PaymentInfo;

class RewardGiftOrderPlacementStrategy extends AbstractOrderPlacementStrategy {

    RewardGiftOrderPlacementStrategy(OrderLifecycleServiceImpl service) {
        super(service);
    }

    @Override
    protected OrderAmountBreakdown handlePricing(OrderPlacementCommand command, OrderCreationContext context) {
        if (context.getRewardType() != OrderConstant.RewardType.GIFT) {
            throw new CustomException("礼物订单类型不匹配");
        }

        PaymentInfo normalized = ensurePaymentInfoPresent(context);
        return service.fallbackBreakdown(normalized);
    }

    private PaymentInfo ensurePaymentInfoPresent(OrderCreationContext context) {
        PaymentInfo info = context.getPaymentInfo();
        if (info == null) {
            throw new CustomException("支付信息不能为空");
        }
        PaymentInfo normalized = PaymentInfo.builder()
                .orderMoney(service.normalizeMoney(info.getOrderMoney()))
                .discountAmount(service.normalizeMoney(info.getDiscountAmount()))
                .finalAmount(service.normalizeMoney(info.getFinalAmount()))
                .couponIds(info.getCouponIds())
                .payMethod(info.getPayMethod())
                .paymentSource(info.getPaymentSource())
                .build();
        context.setPaymentInfo(normalized);
        return normalized;
    }
}
