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

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import com.jeesharp.business.modules.coupon.dto.CouponCheckoutContextDTO;
import com.jeesharp.business.modules.coupon.enums.CouponSceneCodeEnum;
import com.jeesharp.business.modules.mall.dto.MallOrderSubmitLineDTO;
import com.jeesharp.business.modules.mall.entity.MallSpu;
import com.jeesharp.business.modules.mall.service.MallSpuService;
import lombok.AllArgsConstructor;
import org.springframework.stereotype.Component;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
 * 商城优惠券结账上下文组装，供定价 Support 与订单 Application 试算/冻结复用。
 *
 * @author jeesharp
 * @since 2026-06-10
 */
@Component
@AllArgsConstructor
public class MallCouponCheckoutContextSupport {

    private final MallSpuService mallSpuService;

    /**
     * 组装商城结账上下文：场景 MALL + 购物车 SPU/分类/品牌，供优惠券试算与冻结。
     *
     * <p>scopeItemIds=SPU 列表，用于「指定商品可用」类券；categoryIds/brandIds 用于品类/品牌范围券。</p>
     */
    public CouponCheckoutContextDTO buildContext(String memberId, BigDecimal orderAmount,
                                                 List<MallOrderSubmitLineDTO> items) {
        CouponCheckoutContextDTO context = new CouponCheckoutContextDTO();
        context.setMemberId(memberId);
        context.setSceneCode(CouponSceneCodeEnum.MALL.getCode());
        context.setPlatform("MINI");
        context.setOrderAmount(orderAmount);
        if (CollUtil.isEmpty(items)) {
            return context;
        }
        List<String> spuIds = new ArrayList<>();
        Set<String> categoryIds = new HashSet<>();
        Set<String> brandIds = new HashSet<>();
        for (MallOrderSubmitLineDTO line : items) {
            if (line == null || StrUtil.isBlank(line.getSpuId())) {
                continue;
            }
            String spuId = line.getSpuId().trim();
            spuIds.add(spuId);
            MallSpu spu = mallSpuService.get(spuId);
            if (spu != null) {
                if (StrUtil.isNotBlank(spu.getCategoryId())) {
                    categoryIds.add(spu.getCategoryId().trim());
                }
                if (StrUtil.isNotBlank(spu.getBrandId())) {
                    brandIds.add(spu.getBrandId().trim());
                }
            }
        }
        context.setScopeItemIds(spuIds);
        context.setCategoryIds(new ArrayList<>(categoryIds));
        context.setBrandIds(new ArrayList<>(brandIds));
        return context;
    }
}
