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

import static org.junit.jupiter.api.Assertions.assertInstanceOf;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.lenient;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.put;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
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.Spy;
import org.mockito.junit.jupiter.MockitoExtension;
import org.springframework.http.MediaType;
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.fasterxml.jackson.databind.ObjectMapper;
import com.ruoyi.web.modules.category.support.SellerShopContext;
import com.ruoyi.web.modules.store.dto.SellerShopProfileDTO;
import com.ruoyi.web.modules.store.service.IShopService;
import com.ruoyi.web.modules.store.vo.SellerShopEmployeeStatsVO;
import com.ruoyi.web.modules.store.vo.SellerShopProfileVO;

@ExtendWith(MockitoExtension.class)
class SellerShopControllerTest
{
    @Mock
    private IShopService shopService;

    @Spy
    @InjectMocks
    private SellerShopController controller;

    private MockMvc mockMvc;

    private final ObjectMapper objectMapper = new ObjectMapper();

    @BeforeEach
    void setUp() throws Exception
    {
        SellerShopContext.setShopId(1L);
        mockMvc = MockMvcBuilders.standaloneSetup(controller).build();
        lenient().doReturn("seller").when(controller).getUsername();
    }

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

    @Test
    void getProfile_returnsShopFields() throws Exception
    {
        SellerShopProfileVO vo = new SellerShopProfileVO();
        vo.setShopId(1L);
        vo.setShopName("测试店");
        vo.setShopAvatar("/a.jpg");
        vo.setShopPhone("010-88886666");
        vo.setShopStatus("0");
        vo.setContactName("张三");
        vo.setContactPhone("138****8000");
        when(shopService.selectSellerShopProfile(1L)).thenReturn(vo);

        mockMvc.perform(get("/agri/seller/shop"))
                .andExpect(status().isOk())
                .andExpect(jsonPath("$.data.shopName").value("测试店"))
                .andExpect(jsonPath("$.data.contactName").value("张三"));
    }

    @Test
    void getProfile_withoutShopId_rejected()
    {
        SellerShopContext.clear();

        NestedServletException ex = assertThrows(NestedServletException.class,
                () -> mockMvc.perform(get("/agri/seller/shop")).andReturn());
        assertInstanceOf(ServiceException.class, ex.getCause());

        verify(shopService, never()).selectSellerShopProfile(org.mockito.ArgumentMatchers.any());
    }

    @Test
    void updateProfile_delegatesToService() throws Exception
    {
        SellerShopProfileDTO dto = new SellerShopProfileDTO();
        dto.setShopName("新店名");
        dto.setShopAvatar("/b.jpg");
        dto.setShopPhone("010-88886667");

        mockMvc.perform(put("/agri/seller/shop")
                .contentType(MediaType.APPLICATION_JSON)
                .content(objectMapper.writeValueAsString(dto)))
                .andExpect(status().isOk());

        verify(shopService).updateSellerShopProfile(eq(1L), org.mockito.ArgumentMatchers.any(), eq("seller"));
    }

    @Test
    void updateProfile_withoutShopId_rejected() throws Exception
    {
        SellerShopContext.clear();
        SellerShopProfileDTO dto = new SellerShopProfileDTO();
        dto.setShopName("新店名");
        dto.setShopAvatar("/b.jpg");

        NestedServletException ex = assertThrows(NestedServletException.class,
                () -> mockMvc.perform(put("/agri/seller/shop")
                        .contentType(MediaType.APPLICATION_JSON)
                        .content(objectMapper.writeValueAsString(dto)))
                        .andReturn());
        assertInstanceOf(ServiceException.class, ex.getCause());

        verify(shopService, never()).updateSellerShopProfile(
                org.mockito.ArgumentMatchers.any(), org.mockito.ArgumentMatchers.any(), org.mockito.ArgumentMatchers.any());
    }

    @Test
    void employeeStats_returnsCounts() throws Exception
    {
        SellerShopEmployeeStatsVO stats = new SellerShopEmployeeStatsVO();
        stats.setShopId(1L);
        stats.setShopName("测试店");
        stats.setTotalCount(2);
        stats.setDisabledCount(1);
        stats.setUsedCount(3);
        stats.setMaxCount(5);
        when(shopService.selectSellerEmployeeStats(1L)).thenReturn(stats);

        mockMvc.perform(get("/agri/seller/shop/employeeStats"))
                .andExpect(status().isOk())
                .andExpect(jsonPath("$.data.totalCount").value(2))
                .andExpect(jsonPath("$.data.disabledCount").value(1))
                .andExpect(jsonPath("$.data.usedCount").value(3))
                .andExpect(jsonPath("$.data.maxCount").value(5));
    }

    @Test
    void employeeStats_withoutShopId_rejected()
    {
        SellerShopContext.clear();

        NestedServletException ex = assertThrows(NestedServletException.class,
                () -> mockMvc.perform(get("/agri/seller/shop/employeeStats")).andReturn());
        assertInstanceOf(ServiceException.class, ex.getCause());

        verify(shopService, never()).selectSellerEmployeeStats(org.mockito.ArgumentMatchers.any());
    }
}
