package com.jeesharp.business.member.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.entity.MallSpu;
import com.jeesharp.business.modules.mall.service.MallSpuService;
import lombok.AllArgsConstructor;
import org.springframework.stereotype.Component;

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

/**
 * 移动端商城场景结账上下文补全：由 SPU 主键解析分类、品牌，供优惠券范围匹配。
 *
 * @author jeesharp
 * @since 2026-06-06
 */
@Component
@AllArgsConstructor
public class CouponMallCheckoutContextEnricher {

    private final MallSpuService mallSpuService;

    /**
     * 当场景为 MALL 且已传 SPU 列表时，补全 {@code categoryIds}、{@code brandIds}（不覆盖已有非空列表）。
     */
    public void enrich(CouponCheckoutContextDTO context) {
        if (context == null || StrUtil.isBlank(context.getSceneCode())) {
            return;
        }
        if (!CouponSceneCodeEnum.MALL.getCode().equalsIgnoreCase(context.getSceneCode().trim())) {
            return;
        }
        if (CollUtil.isEmpty(context.getScopeItemIds())) {
            return;
        }
        if (CollUtil.isNotEmpty(context.getCategoryIds()) && CollUtil.isNotEmpty(context.getBrandIds())) {
            return;
        }
        Set<String> categoryIds = new HashSet<>();
        Set<String> brandIds = new HashSet<>();
        for (String spuId : context.getScopeItemIds()) {
            if (StrUtil.isBlank(spuId)) {
                continue;
            }
            MallSpu spu = mallSpuService.get(spuId.trim());
            if (spu == null) {
                continue;
            }
            if (StrUtil.isNotBlank(spu.getCategoryId())) {
                categoryIds.add(spu.getCategoryId().trim());
            }
            if (StrUtil.isNotBlank(spu.getBrandId())) {
                brandIds.add(spu.getBrandId().trim());
            }
        }
        if (CollUtil.isEmpty(context.getCategoryIds()) && CollUtil.isNotEmpty(categoryIds)) {
            context.setCategoryIds(new ArrayList<>(categoryIds));
        }
        if (CollUtil.isEmpty(context.getBrandIds()) && CollUtil.isNotEmpty(brandIds)) {
            context.setBrandIds(new ArrayList<>(brandIds));
        }
    }
}
