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.ArgumentMatchers.eq;
import static org.mockito.ArgumentMatchers.isNull;
import static org.mockito.Mockito.doNothing;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.delete;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
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.Collections;
import org.junit.jupiter.api.AfterEach;
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.framework.web.service.TokenService;
import com.ruoyi.web.modules.account.support.MemberContext;
import com.ruoyi.web.modules.category.vo.CategoryVisibleChildVO;
import com.ruoyi.web.modules.category.vo.CategoryVisibleVO;
import com.ruoyi.web.modules.home.constant.ShopAppConstants;
import com.ruoyi.web.modules.home.service.IShopAppService;
import com.ruoyi.web.modules.home.vo.HomeHotGoodsVO;
import com.ruoyi.web.modules.home.vo.ShopProfileAppVO;

/**
 * C 端店铺主页接口测试
 */
@ExtendWith(MockitoExtension.class)
class ShopAppControllerTest
{
    private static final Long SHOP_ID = 101L;

    private static final Long MEMBER_ID = 200L;

    @Mock
    private IShopAppService shopAppService;

    @Mock
    private TokenService tokenService;

    @InjectMocks
    private ShopAppController controller;

    private MockMvc mockMvc;

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

    @AfterEach
    void tearDown()
    {
        MemberContext.clear();
    }

    @Test
    void profile_returns200WithoutToken() throws Exception
    {
        ShopProfileAppVO profile = profile(false);
        when(shopAppService.getProfile(eq(SHOP_ID), isNull())).thenReturn(profile);

        mockMvc.perform(get("/api/shop/{shopId}", SHOP_ID))
                .andExpect(status().isOk())
                .andExpect(jsonPath("$.code").value(200))
                .andExpect(jsonPath("$.data.shopId").value(101))
                .andExpect(jsonPath("$.data.shopName").value("测试店"))
                .andExpect(jsonPath("$.data.fansCount").value(3))
                .andExpect(jsonPath("$.data.followed").value(false));
    }

    @Test
    void categories_returns200() throws Exception
    {
        CategoryVisibleVO l1 = new CategoryVisibleVO();
        l1.setCategoryId(1L);
        l1.setCategoryName("农资");
        when(shopAppService.listCategories(SHOP_ID)).thenReturn(Collections.singletonList(l1));

        mockMvc.perform(get("/api/shop/{shopId}/categories", SHOP_ID))
                .andExpect(status().isOk())
                .andExpect(jsonPath("$.code").value(200))
                .andExpect(jsonPath("$.data[0].categoryName").value("农资"));
    }

    @Test
    void level2Tabs_returns200() throws Exception
    {
        CategoryVisibleChildVO tab = new CategoryVisibleChildVO();
        tab.setCategoryId(11L);
        tab.setCategoryName("肥料");
        when(shopAppService.listLevel2Tabs(SHOP_ID, 1L)).thenReturn(Collections.singletonList(tab));

        mockMvc.perform(get("/api/shop/{shopId}/categories/{level1Id}/level2-tabs", SHOP_ID, 1L))
                .andExpect(status().isOk())
                .andExpect(jsonPath("$.data[0].categoryName").value("肥料"));
    }

    @Test
    void goods_returns200WithPagination() throws Exception
    {
        when(shopAppService.listGoods(eq(SHOP_ID), any())).thenReturn(Collections.singletonList(goods()));

        mockMvc.perform(get("/api/shop/{shopId}/goods", SHOP_ID)
                .param("pageNum", "1")
                .param("pageSize", "10"))
                .andExpect(status().isOk())
                .andExpect(jsonPath("$.code").value(200))
                .andExpect(jsonPath("$.rows[0].goodsId").value(1));
    }

    @Test
    void goods_searchByKeyword() throws Exception
    {
        when(shopAppService.listGoods(eq(SHOP_ID), any())).thenReturn(Collections.singletonList(goods()));

        mockMvc.perform(get("/api/shop/{shopId}/goods", SHOP_ID).param("keyword", "化肥"))
                .andExpect(status().isOk())
                .andExpect(jsonPath("$.rows[0].goodsName").value("测试商品"));
    }

    @Test
    void goods_shopNotFoundRejected()
    {
        when(shopAppService.listGoods(eq(SHOP_ID), any()))
                .thenThrow(new ServiceException(ShopAppConstants.MSG_SHOP_NOT_FOUND));

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

    @Test
    void follow_requiresLogin() throws Exception
    {
        NestedServletException ex = assertThrows(NestedServletException.class,
                () -> mockMvc.perform(post("/api/shop/{shopId}/follow", SHOP_ID)).andReturn());
        assertInstanceOf(ServiceException.class, ex.getCause());
    }

    @Test
    void follow_returns200WhenLoggedIn() throws Exception
    {
        MemberContext.setMemberId(MEMBER_ID);
        doNothing().when(shopAppService).follow(SHOP_ID, MEMBER_ID);

        mockMvc.perform(post("/api/shop/{shopId}/follow", SHOP_ID))
                .andExpect(status().isOk())
                .andExpect(jsonPath("$.code").value(200));

        verify(shopAppService).follow(SHOP_ID, MEMBER_ID);
    }

    @Test
    void unfollow_returns200WhenLoggedIn() throws Exception
    {
        MemberContext.setMemberId(MEMBER_ID);
        doNothing().when(shopAppService).unfollow(SHOP_ID, MEMBER_ID);

        mockMvc.perform(delete("/api/shop/{shopId}/follow", SHOP_ID))
                .andExpect(status().isOk())
                .andExpect(jsonPath("$.code").value(200));

        verify(shopAppService).unfollow(SHOP_ID, MEMBER_ID);
    }

    private static ShopProfileAppVO profile(boolean followed)
    {
        ShopProfileAppVO vo = new ShopProfileAppVO();
        vo.setShopId(SHOP_ID);
        vo.setShopName("测试店");
        vo.setShopAvatar("/avatar.jpg");
        vo.setShopStatus("0");
        vo.setFansCount(3);
        vo.setFollowed(followed);
        return vo;
    }

    private static HomeHotGoodsVO goods()
    {
        HomeHotGoodsVO vo = new HomeHotGoodsVO();
        vo.setGoodsId(1L);
        vo.setGoodsSn("G001");
        vo.setGoodsName("测试商品");
        vo.setMainPic("/pic.jpg");
        vo.setSalePrice(new BigDecimal("88.50"));
        vo.setShopId(SHOP_ID);
        vo.setShopName("测试店");
        return vo;
    }
}
