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

import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.doThrow;
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.request.MockMvcRequestBuilders.put;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
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.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 com.fasterxml.jackson.databind.ObjectMapper;
import com.ruoyi.web.modules.category.support.SellerShopContext;
import com.ruoyi.web.modules.template.dto.AttrTemplateItemDTO;
import com.ruoyi.web.modules.template.dto.AttrTemplateSaveDTO;
import com.ruoyi.web.modules.template.exception.AttrTemplateBatchDeleteException;
import com.ruoyi.web.modules.template.service.IAttrTemplateService;
import com.ruoyi.web.modules.template.vo.AttrTemplateDetailVO;
import com.ruoyi.web.modules.template.vo.AttrTemplateListVO;
import com.ruoyi.web.modules.template.vo.AttrTemplateOptionVO;

@ExtendWith(MockitoExtension.class)
class SellerAttrTemplateControllerTest
{
    @Mock
    private IAttrTemplateService attrTemplateService;

    @Spy
    @InjectMocks
    private SellerAttrTemplateController controller;

    private MockMvc mockMvc;

    private final ObjectMapper objectMapper = new ObjectMapper();

    @BeforeEach
    void setUp()
    {
        SellerShopContext.setShopId(101L);
        mockMvc = MockMvcBuilders.standaloneSetup(controller).build();
        org.mockito.Mockito.lenient().doReturn("tester").when(controller).getUsername();
    }

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

    @Test
    void list_returns200() throws Exception
    {
        AttrTemplateListVO row = new AttrTemplateListVO();
        row.setTemplateId(1L);
        row.setTemplateName("宠物");
        row.setNameList("类型,品种");
        when(attrTemplateService.selectTemplateList(null)).thenReturn(Collections.singletonList(row));

        mockMvc.perform(get("/agri/seller/attrTemplate/list"))
                .andExpect(status().isOk())
                .andExpect(jsonPath("$.code").value(200))
                .andExpect(jsonPath("$.rows[0].templateName").value("宠物"))
                .andExpect(jsonPath("$.rows[0].nameList").value("类型,品种"));
    }

    @Test
    void getInfo_returns200() throws Exception
    {
        AttrTemplateDetailVO detail = new AttrTemplateDetailVO();
        detail.setTemplateId(2L);
        detail.setTemplateName("手机");
        when(attrTemplateService.selectTemplateDetail(2L)).thenReturn(detail);

        mockMvc.perform(get("/agri/seller/attrTemplate/2"))
                .andExpect(status().isOk())
                .andExpect(jsonPath("$.code").value(200))
                .andExpect(jsonPath("$.data.templateName").value("手机"));
    }

    @Test
    void add_returns200() throws Exception
    {
        when(attrTemplateService.insertTemplate(any(), any())).thenReturn(1);

        AttrTemplateSaveDTO body = new AttrTemplateSaveDTO();
        body.setTemplateName("家电");
        AttrTemplateItemDTO attr = new AttrTemplateItemDTO();
        attr.setItemName("功率");
        attr.setValues(Collections.singletonList("1000W"));
        body.setAttributes(Collections.singletonList(attr));

        mockMvc.perform(post("/agri/seller/attrTemplate")
                .contentType(MediaType.APPLICATION_JSON)
                .content(objectMapper.writeValueAsString(body)))
                .andExpect(status().isOk())
                .andExpect(jsonPath("$.code").value(200));
    }

    @Test
    void edit_returns200() throws Exception
    {
        when(attrTemplateService.updateTemplate(any(), any())).thenReturn(1);

        AttrTemplateSaveDTO body = new AttrTemplateSaveDTO();
        body.setTemplateId(2L);
        body.setTemplateName("手机Pro");
        AttrTemplateItemDTO attr = new AttrTemplateItemDTO();
        attr.setItemName("品牌");
        attr.setValues(Collections.singletonList("小米"));
        body.setAttributes(Collections.singletonList(attr));

        mockMvc.perform(put("/agri/seller/attrTemplate")
                .contentType(MediaType.APPLICATION_JSON)
                .content(objectMapper.writeValueAsString(body)))
                .andExpect(status().isOk())
                .andExpect(jsonPath("$.code").value(200));
    }

    @Test
    void options_returns200() throws Exception
    {
        AttrTemplateOptionVO opt = new AttrTemplateOptionVO();
        opt.setTemplateId(1L);
        opt.setTemplateName("宠物");
        when(attrTemplateService.selectOptions()).thenReturn(Collections.singletonList(opt));

        mockMvc.perform(get("/agri/seller/attrTemplate/options"))
                .andExpect(status().isOk())
                .andExpect(jsonPath("$.code").value(200))
                .andExpect(jsonPath("$.data[0].templateName").value("宠物"));
    }

    @Test
    void remove_batchFail_returnsReasons() throws Exception
    {
        doThrow(new AttrTemplateBatchDeleteException("部分属性模版不满足删除条件，整批操作已取消",
                Collections.singletonList("属性模版「引用中」已被商品使用，无法删除")))
                .when(attrTemplateService).deleteTemplateByIds(any(), any());

        mockMvc.perform(delete("/agri/seller/attrTemplate/4"))
                .andExpect(status().isOk())
                .andExpect(jsonPath("$.code").value(500))
                .andExpect(jsonPath("$.data.reasons[0]").exists());
    }

    @Test
    void remove_success() throws Exception
    {
        org.mockito.Mockito.doNothing().when(attrTemplateService).deleteTemplateByIds(any(), any());

        mockMvc.perform(delete("/agri/seller/attrTemplate/3"))
                .andExpect(status().isOk())
                .andExpect(jsonPath("$.code").value(200));
    }

    @Test
    void list_withKeyword() throws Exception
    {
        when(attrTemplateService.selectTemplateList("手")).thenReturn(Collections.emptyList());

        mockMvc.perform(get("/agri/seller/attrTemplate/list").param("keyword", "手"))
                .andExpect(status().isOk())
                .andExpect(jsonPath("$.code").value(200));
    }
}
