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

import com.jeesharp.business.modules.coupon.entity.MemberCoupon;
import com.jeesharp.business.modules.coupon.enums.CouponDiscountTypeEnum;

import java.math.BigDecimal;
import java.math.RoundingMode;

/**
 * 会员券抵扣金额计算，供试算（listForCheckout/resolveDiscount）与冻结（freezeForOrder）共用。
 *
 * <p>规则：AMOUNT=固定面额（不超过 orderAmount）；RATE=折扣（discountValue 为「几折」，如 8.5 表示 8.5 折，
 * 可受 maxDiscountAmount 封顶）。</p>
 *
 * @author jeesharp
 * @since 2026-06-05
 */
public final class CouponDiscountCalculator {

    private CouponDiscountCalculator() {
    }

    public static BigDecimal compute(MemberCoupon coupon, BigDecimal orderAmount) {
        if (coupon == null || orderAmount == null || orderAmount.compareTo(BigDecimal.ZERO) < 0) {
            return BigDecimal.ZERO.setScale(2, RoundingMode.HALF_UP);
        }
        if (CouponDiscountTypeEnum.AMOUNT.getValue().equals(coupon.getDiscountType())) {
            BigDecimal v = coupon.getDiscountValue() != null ? coupon.getDiscountValue() : BigDecimal.ZERO;
            return v.min(orderAmount).setScale(2, RoundingMode.HALF_UP);
        }
        if (CouponDiscountTypeEnum.RATE.getValue().equals(coupon.getDiscountType()) && coupon.getDiscountValue() != null) {
            BigDecimal rate = coupon.getDiscountValue().divide(BigDecimal.TEN, 4, RoundingMode.HALF_UP);
            BigDecimal pay = orderAmount.multiply(rate).setScale(2, RoundingMode.HALF_UP);
            BigDecimal discount = orderAmount.subtract(pay).max(BigDecimal.ZERO);
            if (coupon.getMaxDiscountAmount() != null) {
                discount = discount.min(coupon.getMaxDiscountAmount());
            }
            return discount.setScale(2, RoundingMode.HALF_UP);
        }
        return BigDecimal.ZERO.setScale(2, RoundingMode.HALF_UP);
    }
}
