package com.ruoyi.web.modules.home.controller;

import static org.junit.jupiter.api.Assertions.assertInstanceOf;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.when;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
import java.math.BigDecimal;
import java.util.Arrays;
import java.util.Collections;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import org.springframework.web.util.NestedServletException;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.web.modules.category.vo.CategoryVisibleChildVO;
import com.ruoyi.web.modules.category.vo.CategoryVisibleVO;
import com.ruoyi.web.modules.home.constant.CategoryAppConstants;
import com.ruoyi.web.modules.home.service.ICategoryAppService;
import com.ruoyi.web.modules.home.vo.HomeHotGoodsVO;

/**
 * C 端商品分类接口测试（CGC-API-001～020）
 */
@ExtendWith(MockitoExtension.class)
class CategoryAppControllerTest
{
    @Mock
    private ICategoryAppService categoryAppService;

    @InjectMocks
    private CategoryAppController controller;

    private MockMvc mockMvc;

    @BeforeEach
    void setUp()
    {
        mockMvc = MockMvcBuilders.standaloneSetup(controller).build();
    }

    @Test
    void tree_returns200WithoutToken() throws Exception
    {
        CategoryVisibleVO l1 = new CategoryVisibleVO();
        l1.setCategoryId(1L);
        l1.setCategoryName("兽药");
        l1.setSortNo(0);
        CategoryVisibleChildVO child = new CategoryVisibleChildVO();
        child.setCategoryId(11L);
        child.setCategoryName("抗生素");
        l1.getChildren().add(child);
        when(categoryAppService.listCategoryTree()).thenReturn(Collections.singletonList(l1));

        mockMvc.perform(get("/api/category/tree"))
                .andExpect(status().isOk())
                .andExpect(jsonPath("$.code").value(200))
                .andExpect(jsonPath("$.data[0].categoryId").value(1))
                .andExpect(jsonPath("$.data[0].categoryName").value("兽药"))
                .andExpect(jsonPath("$.data[0].children[0].categoryId").value(11))
                .andExpect(jsonPath("$.data[0].children[0].categoryName").value("抗生素"));
    }

    @Test
    void tree_emptyList() throws Exception
    {
        when(categoryAppService.listCategoryTree()).thenReturn(Collections.emptyList());

        mockMvc.perform(get("/api/category/tree"))
                .andExpect(status().isOk())
                .andExpect(jsonPath("$.code").value(200))
                .andExpect(jsonPath("$.data").isArray())
                .andExpect(jsonPath("$.data").isEmpty());
    }

    @Test
    void level2Tabs_returns200() throws Exception
    {
        CategoryVisibleChildVO tab1 = new CategoryVisibleChildVO();
        tab1.setCategoryId(11L);
        tab1.setCategoryName("抗生素");
        tab1.setSortNo(0);
        CategoryVisibleChildVO tab2 = new CategoryVisibleChildVO();
        tab2.setCategoryId(12L);
        tab2.setCategoryName("驱虫药");
        tab2.setSortNo(1);
        when(categoryAppService.listLevel2Tabs(1L)).thenReturn(Arrays.asList(tab1, tab2));

        mockMvc.perform(get("/api/category/1/level2-tabs"))
                .andExpect(status().isOk())
                .andExpect(jsonPath("$.code").value(200))
                .andExpect(jsonPath("$.data.length()").value(2))
                .andExpect(jsonPath("$.data[0].categoryName").value("抗生素"));
    }

    @Test
    void level2Tabs_invalidLevel1Rejected()
    {
        when(categoryAppService.listLevel2Tabs(99999L))
                .thenThrow(new ServiceException(CategoryAppConstants.MSG_CATEGORY_INVISIBLE));

        NestedServletException ex = assertThrows(NestedServletException.class,
                () -> mockMvc.perform(get("/api/category/99999/level2-tabs")).andReturn());
        assertInstanceOf(ServiceException.class, ex.getCause());
    }

    @Test
    void goods_returns200WithPagination() throws Exception
    {
        when(categoryAppService.listCategoryGoods(any())).thenReturn(Collections.singletonList(goods(1L, "G001")));

        mockMvc.perform(get("/api/category/goods")
                .param("categoryId", "11")
                .param("pageNum", "1")
                .param("pageSize", "10"))
                .andExpect(status().isOk())
                .andExpect(jsonPath("$.code").value(200))
                .andExpect(jsonPath("$.rows[0].goodsId").value(1))
                .andExpect(jsonPath("$.rows[0].goodsSn").value("G001"))
                .andExpect(jsonPath("$.rows[0].goodsName").value("测试商品"))
                .andExpect(jsonPath("$.rows[0].mainPic").value("/pic/g1.jpg"))
                .andExpect(jsonPath("$.rows[0].salePrice").value(88.50))
                .andExpect(jsonPath("$.rows[0].shopId").value(101))
                .andExpect(jsonPath("$.rows[0].shopName").value("测试店"));
    }

    @Test
    void goods_missingCategoryIdRejected()
    {
        when(categoryAppService.listCategoryGoods(any()))
                .thenThrow(new ServiceException(CategoryAppConstants.MSG_CATEGORY_REQUIRED));

        NestedServletException ex = assertThrows(NestedServletException.class,
                () -> mockMvc.perform(get("/api/category/goods")).andReturn());
        assertInstanceOf(ServiceException.class, ex.getCause());
    }

    @Test
    void goods_invisibleCategoryRejected()
    {
        when(categoryAppService.listCategoryGoods(any()))
                .thenThrow(new ServiceException(CategoryAppConstants.MSG_CATEGORY_INVISIBLE));

        NestedServletException ex = assertThrows(NestedServletException.class,
                () -> mockMvc.perform(get("/api/category/goods").param("categoryId", "99")).andReturn());
        assertInstanceOf(ServiceException.class, ex.getCause());
    }

    @Test
    void goods_invalidSortRejected()
    {
        when(categoryAppService.listCategoryGoods(any()))
                .thenThrow(new ServiceException(CategoryAppConstants.MSG_SORT_INVALID));

        NestedServletException ex = assertThrows(NestedServletException.class,
                () -> mockMvc.perform(get("/api/category/goods")
                        .param("categoryId", "11")
                        .param("sortBy", "foo")).andReturn());
        assertInstanceOf(ServiceException.class, ex.getCause());
    }

    @Test
    void goods_emptyList() throws Exception
    {
        when(categoryAppService.listCategoryGoods(any())).thenReturn(Collections.emptyList());

        mockMvc.perform(get("/api/category/goods").param("categoryId", "11"))
                .andExpect(status().isOk())
                .andExpect(jsonPath("$.code").value(200))
                .andExpect(jsonPath("$.rows").isArray())
                .andExpect(jsonPath("$.rows").isEmpty());
    }

    @Test
    void goods_returnsMultipleItems() throws Exception
    {
        when(categoryAppService.listCategoryGoods(any())).thenReturn(Arrays.asList(
                goods(1L, "G001"),
                goods(2L, "G002")));

        mockMvc.perform(get("/api/category/goods").param("categoryId", "11"))
                .andExpect(status().isOk())
                .andExpect(jsonPath("$.rows.length()").value(2));
    }

    @Test
    void goods_preservesOrder() throws Exception
    {
        when(categoryAppService.listCategoryGoods(any())).thenReturn(Arrays.asList(
                goods(1L, "G001"),
                goods(3L, "G003")));

        mockMvc.perform(get("/api/category/goods").param("categoryId", "11"))
                .andExpect(status().isOk())
                .andExpect(jsonPath("$.rows[0].goodsId").value(1))
                .andExpect(jsonPath("$.rows[1].goodsId").value(3));
    }

    private static HomeHotGoodsVO goods(Long goodsId, String goodsSn)
    {
        HomeHotGoodsVO vo = new HomeHotGoodsVO();
        vo.setGoodsId(goodsId);
        vo.setGoodsSn(goodsSn);
        vo.setGoodsName("测试商品");
        vo.setMainPic("/pic/g1.jpg");
        vo.setSalePrice(new BigDecimal("88.50"));
        vo.setShopId(101L);
        vo.setShopName("测试店");
        return vo;
    }
}
