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

import cn.hutool.core.util.StrUtil;
import com.jeesharp.business.modules.coupon.api.MemberCouponGrantApi;
import com.jeesharp.business.modules.coupon.dto.MemberCouponGrantDTO;
import com.jeesharp.business.modules.mall.entity.MallFirstOrderConfig;
import com.jeesharp.business.modules.mall.service.MallFirstOrderConfigService;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 商城首单优惠编排：立减计算与支付后赠券；供订单 Application 与首单配置 Application 复用。
 *
 * @author jeesharp
 * @since 2026-06-09
 */
@Slf4j
@Component
@AllArgsConstructor
@Transactional(readOnly = true)
public class MallFirstOrderPromoSupport {

    private static final String COUPON_GRANT_REMARK = "首单优惠赠券";

    private final MallFirstOrderConfigService mallFirstOrderConfigService;
    private final MemberCouponGrantApi memberCouponGrantApi;

    public BigDecimal resolveFirstOrderDiscount(String memberId, BigDecimal payableBeforeDiscount) {
        if (StrUtil.isBlank(memberId) || payableBeforeDiscount == null
                || payableBeforeDiscount.compareTo(BigDecimal.ZERO) <= 0) {
            return BigDecimal.ZERO.setScale(2, RoundingMode.HALF_UP);
        }
        if (!mallFirstOrderConfigService.checkIsFirstOrder(memberId)) {
            return BigDecimal.ZERO.setScale(2, RoundingMode.HALF_UP);
        }
        MallFirstOrderConfig config = mallFirstOrderConfigService.getEnabledConfig();
        if (config == null || config.getDiscountAmount() == null
                || config.getDiscountAmount().compareTo(BigDecimal.ZERO) <= 0) {
            return BigDecimal.ZERO.setScale(2, RoundingMode.HALF_UP);
        }
        BigDecimal discount = config.getDiscountAmount().setScale(2, RoundingMode.HALF_UP);
        if (discount.compareTo(payableBeforeDiscount) > 0) {
            return payableBeforeDiscount.setScale(2, RoundingMode.HALF_UP);
        }
        return discount;
    }

    @Transactional(readOnly = false)
    public void tryGrantCouponsAfterFirstPaidOrder(String memberId) {
        if (StrUtil.isBlank(memberId) || !mallFirstOrderConfigService.isFirstPaidOrder(memberId)) {
            return;
        }
        MallFirstOrderConfig config = mallFirstOrderConfigService.getEnabledConfig();
        if (config == null || StrUtil.isBlank(config.getCouponTemplateIds())) {
            return;
        }
        List<String> templateIds = splitTemplateIds(config.getCouponTemplateIds());
        for (String templateId : templateIds) {
            try {
                MemberCouponGrantDTO grant = new MemberCouponGrantDTO();
                grant.setTemplateId(templateId);
                grant.setMemberIds(Collections.singletonList(memberId));
                grant.setRemarks(COUPON_GRANT_REMARK);
                memberCouponGrantApi.grantByAdmin(grant);
            } catch (Exception ex) {
                log.warn("首单赠券失败 memberId={} templateId={}: {}", memberId, templateId, ex.getMessage());
            }
        }
    }

    private static List<String> splitTemplateIds(String raw) {
        if (StrUtil.isBlank(raw)) {
            return Collections.emptyList();
        }
        return Arrays.stream(raw.split(","))
                .map(String::trim)
                .filter(StrUtil::isNotBlank)
                .distinct()
                .collect(Collectors.toList());
    }
}
