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

import cn.hutool.core.util.StrUtil;
import com.jeesharp.business.modules.coupon.api.CouponCheckoutApi;
import com.jeesharp.business.modules.coupon.vo.CouponOrderDiscountVO;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.List;
import java.util.Map;

/**
 * 小程序订单 Map 行：按垂直订单号补全优惠券抵扣展示字段（有使用才写入）。
 *
 * @author jeesharp
 * @since 2026-06-09
 */
public final class CouponOrderDisplayRowSupport {

    private CouponOrderDisplayRowSupport() {
    }

    public static void enrichRows(List<Map<String, Object>> rows, CouponCheckoutApi couponCheckoutApi) {
        if (rows == null || rows.isEmpty() || couponCheckoutApi == null) {
            return;
        }
        for (Map<String, Object> row : rows) {
            enrichRow(row, couponCheckoutApi);
        }
    }

    public static void enrichRow(Map<String, Object> row, CouponCheckoutApi couponCheckoutApi) {
        if (row == null || couponCheckoutApi == null) {
            return;
        }
        Object idObj = row.get("id");
        if (idObj == null) {
            return;
        }
        String orderId = String.valueOf(idObj).trim();
        if (orderId.isEmpty()) {
            return;
        }
        CouponOrderDiscountVO vo = couponCheckoutApi.resolveOrderCouponDisplay(orderId);
        if (vo == null || vo.getCouponDiscountAmount() == null
                || vo.getCouponDiscountAmount().compareTo(BigDecimal.ZERO) <= 0) {
            return;
        }
        row.put("couponDiscountAmount", formatMoney(vo.getCouponDiscountAmount()));
        if (StrUtil.isNotBlank(vo.getCouponName())) {
            row.put("couponName", vo.getCouponName().trim());
        }
    }

    private static String formatMoney(BigDecimal amount) {
        if (amount == null) {
            return "0.00";
        }
        return amount.setScale(2, RoundingMode.HALF_UP).toPlainString();
    }
}
