package com.ruoyi.web.modules.freight.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 java.util.HashMap;
import java.util.Map;
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.freight.constant.FreightTemplateConstants;
import com.ruoyi.web.modules.freight.dto.FreightTemplateSaveDTO;
import com.ruoyi.web.modules.freight.exception.FreightTemplateBatchDeleteException;
import com.ruoyi.web.modules.freight.service.IFreightTemplateService;
import com.ruoyi.web.modules.freight.vo.FreightTemplateDetailVO;
import com.ruoyi.web.modules.freight.vo.FreightTemplateListVO;
import com.ruoyi.web.modules.freight.vo.FreightTemplateOptionVO;

@ExtendWith(MockitoExtension.class)
class SellerFreightTemplateControllerTest
{
    @Mock
    private IFreightTemplateService freightTemplateService;

    @Spy
    @InjectMocks
    private SellerFreightTemplateController 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
    {
        FreightTemplateListVO row = new FreightTemplateListVO();
        row.setTemplateId(1L);
        row.setTemplateName("全国包邮");
        row.setFreeFlagLabel("包邮");
        when(freightTemplateService.selectTemplateList(null)).thenReturn(Collections.singletonList(row));

        mockMvc.perform(get("/agri/seller/freightTemplate/list"))
                .andExpect(status().isOk())
                .andExpect(jsonPath("$.code").value(200))
                .andExpect(jsonPath("$.rows[0].templateName").value("全国包邮"));
    }

    @Test
    void getInfo_returns200() throws Exception
    {
        FreightTemplateDetailVO detail = new FreightTemplateDetailVO();
        detail.setTemplateId(2L);
        detail.setTemplateName("江浙沪");
        when(freightTemplateService.selectTemplateDetail(2L)).thenReturn(detail);

        mockMvc.perform(get("/agri/seller/freightTemplate/2"))
                .andExpect(status().isOk())
                .andExpect(jsonPath("$.code").value(200))
                .andExpect(jsonPath("$.data.templateName").value("江浙沪"));
    }

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

        FreightTemplateSaveDTO body = new FreightTemplateSaveDTO();
        body.setTemplateName("全国包邮");
        body.setShipTime("24小时内发货");
        body.setFreeFlag(FreightTemplateConstants.FREE_FLAG_YES);

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

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

        FreightTemplateSaveDTO body = new FreightTemplateSaveDTO();
        body.setTemplateId(2L);
        body.setTemplateName("江浙沪");
        body.setShipTime("48小时内发货");
        body.setFreeFlag(FreightTemplateConstants.FREE_FLAG_YES);

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

    @Test
    void setDefault_returns200() throws Exception
    {
        Map<String, Object> data = new HashMap<>();
        data.put("templateId", 1L);
        data.put("isDefault", "1");
        when(freightTemplateService.setDefaultTemplate(1L, "tester")).thenReturn(data);

        mockMvc.perform(put("/agri/seller/freightTemplate/default/1"))
                .andExpect(status().isOk())
                .andExpect(jsonPath("$.code").value(200))
                .andExpect(jsonPath("$.data.isDefault").value("1"));
    }

    @Test
    void options_returns200() throws Exception
    {
        FreightTemplateOptionVO opt = new FreightTemplateOptionVO();
        opt.setTemplateId(1L);
        opt.setTemplateName("全国包邮");
        when(freightTemplateService.selectOptions()).thenReturn(Collections.singletonList(opt));

        mockMvc.perform(get("/agri/seller/freightTemplate/options"))
                .andExpect(status().isOk())
                .andExpect(jsonPath("$.code").value(200))
                .andExpect(jsonPath("$.data[0].templateName").value("全国包邮"));
    }

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

        mockMvc.perform(delete("/agri/seller/freightTemplate/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(freightTemplateService).deleteTemplateByIds(any(), any());

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