package com.ruoyi.web.modules.goods.support;

import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import org.junit.jupiter.api.Test;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.web.modules.goods.domain.BizGoodsAttr;
import com.ruoyi.web.modules.goods.dto.GoodsAttrItemDTO;
import com.ruoyi.web.modules.template.constant.AttrTemplateConstants;

class GoodsAttrSupportTest
{
    @Test
    void flatten_persistsAttributeAndSpecRows()
    {
        GoodsAttrItemDTO color = new GoodsAttrItemDTO();
        color.setItemName("颜色");
        color.setValues(Arrays.asList("红", "蓝"));
        GoodsAttrItemDTO size = new GoodsAttrItemDTO();
        size.setItemName("尺寸");
        size.setValues(Collections.singletonList("大"));

        List<BizGoodsAttr> rows = GoodsAttrSupport.flatten(1L, Collections.singletonList(color),
                Collections.singletonList(size));

        assertEquals(3, rows.size());
        assertEquals(AttrTemplateConstants.ITEM_TYPE_ATTR, rows.get(0).getAttrType());
        assertEquals("颜色", rows.get(0).getItemName());
        assertEquals("红", rows.get(0).getValueText());
        assertEquals(AttrTemplateConstants.ITEM_TYPE_SPEC, rows.get(2).getAttrType());
        assertEquals("大", rows.get(2).getValueText());
    }

    @Test
    void groupByItem_rebuildsItemsFromRows()
    {
        BizGoodsAttr row1 = new BizGoodsAttr();
        row1.setAttrType(AttrTemplateConstants.ITEM_TYPE_ATTR);
        row1.setItemName("品牌");
        row1.setValueText("华为");
        BizGoodsAttr row2 = new BizGoodsAttr();
        row2.setAttrType(AttrTemplateConstants.ITEM_TYPE_ATTR);
        row2.setItemName("品牌");
        row2.setValueText("荣耀");

        List<GoodsAttrItemDTO> items = GoodsAttrSupport.groupByItem(Arrays.asList(row1, row2),
                AttrTemplateConstants.ITEM_TYPE_ATTR);

        assertEquals(1, items.size());
        assertEquals("品牌", items.get(0).getItemName());
        assertEquals(Arrays.asList("华为", "荣耀"), items.get(0).getValues());
    }

    @Test
    void flatten_rejectsCrossSectionDuplicateName()
    {
        GoodsAttrItemDTO attr = new GoodsAttrItemDTO();
        attr.setItemName("内存");
        attr.setValues(Collections.singletonList("8G"));
        GoodsAttrItemDTO spec = new GoodsAttrItemDTO();
        spec.setItemName("内存");
        spec.setValues(Collections.singletonList("16G"));

        ServiceException ex = assertThrows(ServiceException.class,
                () -> GoodsAttrSupport.flatten(1L, Collections.singletonList(attr),
                        Collections.singletonList(spec)));
        assertTrue(ex.getMessage().contains("不可相同"));
    }
}
