package com.ruoyi.web.modules.stock.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.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.post;
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 org.springframework.web.util.NestedServletException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.web.modules.category.support.SellerShopContext;
import com.ruoyi.web.modules.stock.constant.StockConstants;
import com.ruoyi.web.modules.stock.dto.StockAdjustCreateDTO;
import com.ruoyi.web.modules.stock.service.IStockAdjustService;
import com.ruoyi.web.modules.stock.vo.StockAdjustListRowVO;
import com.ruoyi.web.modules.stock.vo.StockAdjustRecordRowVO;

@ExtendWith(MockitoExtension.class)
class SellerStockAdjustControllerTest
{
    @Mock
    private IStockAdjustService stockAdjustService;

    @Spy
    @InjectMocks
    private SellerStockAdjustController controller;

    private MockMvc mockMvc;

    private final ObjectMapper objectMapper = new ObjectMapper();

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

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

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

        NestedServletException ex = assertThrows(NestedServletException.class,
                () -> mockMvc.perform(get("/agri/seller/stock/adjust/list")).andReturn());
        assertInstanceOf(ServiceException.class, ex.getCause());
        verify(stockAdjustService, never()).selectList(any(), any());
    }

    @Test
    void list_returns200() throws Exception
    {
        StockAdjustListRowVO row = new StockAdjustListRowVO();
        row.setGoodsId(1001L);
        row.setGoodsName("测试商品");
        when(stockAdjustService.selectList(eq(101L), any())).thenReturn(Collections.singletonList(row));

        mockMvc.perform(get("/agri/seller/stock/adjust/list"))
                .andExpect(status().isOk())
                .andExpect(jsonPath("$.code").value(200))
                .andExpect(jsonPath("$.rows[0].goodsId").value(1001));
    }

    @Test
    void adjust_returns200() throws Exception
    {
        Map<String, Object> data = new HashMap<>();
        data.put("adjustId", 1L);
        data.put("stockBefore", 10);
        data.put("stockAfter", 15);
        data.put("adjustTypeText", "增加库存");
        when(stockAdjustService.confirmAdjust(eq(101L), eq(1001L), any(StockAdjustCreateDTO.class), eq(1L), eq("seller01")))
                .thenReturn(data);

        StockAdjustCreateDTO dto = new StockAdjustCreateDTO();
        dto.setAdjustMode(StockConstants.ADJUST_MODE_INCREMENT);
        dto.setAdjustQty(5);

        mockMvc.perform(post("/agri/seller/stock/adjust/1001")
                .contentType(MediaType.APPLICATION_JSON)
                .content(objectMapper.writeValueAsString(dto)))
                .andExpect(status().isOk())
                .andExpect(jsonPath("$.data.stockAfter").value(15));
    }

    @Test
    void records_returns200() throws Exception
    {
        StockAdjustRecordRowVO row = new StockAdjustRecordRowVO();
        row.setAdjustTypeText("覆盖库存");
        row.setStockBefore(10);
        row.setStockAfter(20);
        when(stockAdjustService.listRecords(eq(101L), eq(1001L), any())).thenReturn(Collections.singletonList(row));

        mockMvc.perform(get("/agri/seller/stock/adjust/1001/records"))
                .andExpect(status().isOk())
                .andExpect(jsonPath("$.data[0].adjustTypeText").value("覆盖库存"));
    }
}
