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

import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.doThrow;
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 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.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.facade.ICategoryFacade;
import com.ruoyi.web.modules.goods.constant.GoodsConstants;
import com.ruoyi.web.modules.goods.dto.GoodsAuditDTO;
import com.ruoyi.web.modules.goods.dto.GoodsOffShelfDTO;
import com.ruoyi.web.modules.goods.exception.GoodsBatchOperationException;
import com.ruoyi.web.modules.goods.service.IGoodsService;
import com.ruoyi.web.modules.goods.vo.GoodsDetailVO;

/**
 * 商品审核接口测试（GAU-API）
 */
@ExtendWith(MockitoExtension.class)
class GoodsAuditControllerTest
{
    @Mock
    private IGoodsService goodsService;

    @Mock
    private ICategoryFacade categoryFacade;

    @Spy
    @InjectMocks
    private GoodsAuditController controller;

    private MockMvc mockMvc;

    private final ObjectMapper objectMapper = new ObjectMapper();

    @BeforeEach
    void setUp() throws Exception
    {
        mockMvc = MockMvcBuilders.standaloneSetup(controller).build();
        org.mockito.Mockito.lenient().doReturn("admin").when(controller).getUsername();
    }

    @Test
    void pendingCount_returns200() throws Exception
    {
        when(goodsService.countPlatformPending()).thenReturn(5);

        mockMvc.perform(get("/agri/goodsAudit/pendingCount"))
                .andExpect(status().isOk())
                .andExpect(jsonPath("$.code").value(200))
                .andExpect(jsonPath("$.data.pendingCount").value(5));
    }

    @Test
    void getInfo_pending_canAudit() throws Exception
    {
        GoodsDetailVO vo = new GoodsDetailVO();
        vo.setGoodsId(1L);
        vo.setGoodsStatus(GoodsConstants.STATUS_PENDING);
        vo.setCanAudit(true);
        vo.setCanOffShelf(false);
        when(goodsService.selectPlatformDetail(1L)).thenReturn(vo);

        mockMvc.perform(get("/agri/goodsAudit/1"))
                .andExpect(status().isOk())
                .andExpect(jsonPath("$.code").value(200))
                .andExpect(jsonPath("$.data.canAudit").value(true))
                .andExpect(jsonPath("$.data.canOffShelf").value(false));
    }

    @Test
    void getInfo_onSale_canOffShelf() throws Exception
    {
        GoodsDetailVO vo = new GoodsDetailVO();
        vo.setGoodsId(2L);
        vo.setGoodsStatus(GoodsConstants.STATUS_ON_SALE);
        vo.setCanAudit(false);
        vo.setCanOffShelf(true);
        when(goodsService.selectPlatformDetail(2L)).thenReturn(vo);

        mockMvc.perform(get("/agri/goodsAudit/2"))
                .andExpect(status().isOk())
                .andExpect(jsonPath("$.data.canOffShelf").value(true));
    }

    @Test
    void audit_pass_returns200() throws Exception
    {
        GoodsAuditDTO dto = new GoodsAuditDTO();
        dto.setGoodsIds(Collections.singletonList(10L));
        dto.setPass(true);

        mockMvc.perform(put("/agri/goodsAudit/audit")
                .contentType(MediaType.APPLICATION_JSON)
                .content(objectMapper.writeValueAsString(dto)))
                .andExpect(status().isOk())
                .andExpect(jsonPath("$.code").value(200));

        verify(goodsService).auditGoods(any(GoodsAuditDTO.class), eq("admin"));
    }

    @Test
    void audit_batchFail_returnsReasons() throws Exception
    {
        GoodsAuditDTO dto = new GoodsAuditDTO();
        dto.setGoodsIds(Arrays.asList(1L, 2L));
        dto.setPass(true);
        doThrow(new GoodsBatchOperationException(GoodsConstants.MSG_BATCH_FAIL,
                Collections.singletonList("商品非待审核状态：G001")))
                .when(goodsService).auditGoods(any(), eq("admin"));

        mockMvc.perform(put("/agri/goodsAudit/audit")
                .contentType(MediaType.APPLICATION_JSON)
                .content(objectMapper.writeValueAsString(dto)))
                .andExpect(status().isOk())
                .andExpect(jsonPath("$.code").value(500))
                .andExpect(jsonPath("$.data.reasons[0]").value("商品非待审核状态：G001"));
    }

    @Test
    void offShelf_returns200() throws Exception
    {
        GoodsOffShelfDTO dto = new GoodsOffShelfDTO();
        dto.setGoodsIds(Collections.singletonList(20L));

        mockMvc.perform(put("/agri/goodsAudit/offShelf")
                .contentType(MediaType.APPLICATION_JSON)
                .content(objectMapper.writeValueAsString(dto)))
                .andExpect(status().isOk())
                .andExpect(jsonPath("$.code").value(200));

        verify(goodsService).offShelfPlatform(any(GoodsOffShelfDTO.class), eq("admin"));
    }

    @Test
    void offShelf_batchFail_returnsReasons() throws Exception
    {
        GoodsOffShelfDTO dto = new GoodsOffShelfDTO();
        dto.setGoodsIds(Arrays.asList(1L, 2L));
        doThrow(new GoodsBatchOperationException(GoodsConstants.MSG_BATCH_FAIL,
                Collections.singletonList(GoodsConstants.MSG_OFF_SHELF_INVALID)))
                .when(goodsService).offShelfPlatform(any(), eq("admin"));

        mockMvc.perform(put("/agri/goodsAudit/offShelf")
                .contentType(MediaType.APPLICATION_JSON)
                .content(objectMapper.writeValueAsString(dto)))
                .andExpect(status().isOk())
                .andExpect(jsonPath("$.code").value(500))
                .andExpect(jsonPath("$.data.reasons").isArray());
    }

    @Test
    void categoryOptions_returns200() throws Exception
    {
        when(categoryFacade.listPlatformLevel2Options()).thenReturn(Collections.emptyList());

        mockMvc.perform(get("/agri/goodsAudit/categoryOptions").param("shopId", "1"))
                .andExpect(status().isOk())
                .andExpect(jsonPath("$.code").value(200));
    }
}
