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

import static org.junit.jupiter.api.Assertions.assertFalse;
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.doReturn;
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.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.result.MockMvcResultMatchers.jsonPath;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
import java.math.BigDecimal;
import java.util.Arrays;
import java.util.Collections;
import java.util.Date;
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.order.constant.OrderConstants;
import com.ruoyi.web.modules.order.dto.OrderDeliveredDTO;
import com.ruoyi.web.modules.order.dto.OrderLogisticsDTO;
import com.ruoyi.web.modules.order.dto.OrderShipDTO;
import com.ruoyi.web.modules.order.service.IOrderService;
import com.ruoyi.web.modules.order.vo.OrderDetailVO;
import com.ruoyi.web.modules.order.vo.OrderListRowVO;

@ExtendWith(MockitoExtension.class)
class SellerOrderControllerTest
{
    @Mock
    private IOrderService orderService;

    @Spy
    @InjectMocks
    private SellerOrderController controller;

    private MockMvc mockMvc;

    private final ObjectMapper objectMapper = new ObjectMapper();

    @BeforeEach
    void setUp()
    {
        SellerShopContext.setShopId(101L);
        mockMvc = MockMvcBuilders.standaloneSetup(controller).build();
        lenient().doReturn("seller").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/order/list")).andReturn());
        assertInstanceOf(ServiceException.class, ex.getCause());
        verify(orderService, never()).selectSellerList(any(), any());
    }

    @Test
    void list_returns200() throws Exception
    {
        OrderListRowVO row = new OrderListRowVO();
        row.setOrderId(1L);
        row.setOrderNo("O202605260001");
        row.setOrderStatus(OrderConstants.STATUS_PENDING_SHIP);
        when(orderService.selectSellerList(eq(101L), any())).thenReturn(Collections.singletonList(row));

        mockMvc.perform(get("/agri/seller/order/list"))
                .andExpect(status().isOk())
                .andExpect(jsonPath("$.code").value(200))
                .andExpect(jsonPath("$.rows[0].orderNo").value("O202605260001"));
    }

    @Test
    void detail_returns200() throws Exception
    {
        OrderDetailVO vo = new OrderDetailVO();
        vo.setOrderId(10L);
        vo.setOrderNo("O202605260001");
        vo.setPayAmount(new BigDecimal("99.00"));
        when(orderService.selectSellerDetail(101L, 10L)).thenReturn(vo);

        mockMvc.perform(get("/agri/seller/order/10"))
                .andExpect(status().isOk())
                .andExpect(jsonPath("$.data.orderNo").value("O202605260001"));
    }

    @Test
    void ship_delegatesToService() throws Exception
    {
        OrderShipDTO dto = new OrderShipDTO();
        dto.setShipTime(new Date());
        dto.setDeliveryType(OrderConstants.DELIVERY_LOGISTICS);
        dto.setLogisticsCompany("顺丰");
        dto.setTrackingNo("SF123");

        mockMvc.perform(post("/agri/seller/order/10/ship")
                .contentType(MediaType.APPLICATION_JSON)
                .content(objectMapper.writeValueAsString(dto)))
                .andExpect(status().isOk());

        verify(orderService).shipOrder(eq(101L), eq(10L), any(), eq("seller"));
    }

    @Test
    void logistics_delegatesToService() throws Exception
    {
        OrderLogisticsDTO dto = new OrderLogisticsDTO();
        dto.setTraceTime(new Date());
        dto.setContent("到达拉萨");

        mockMvc.perform(post("/agri/seller/order/10/logistics")
                .contentType(MediaType.APPLICATION_JSON)
                .content(objectMapper.writeValueAsString(dto)))
                .andExpect(status().isOk());

        verify(orderService).appendLogistics(eq(101L), eq(10L), any(), eq("seller"));
    }

    @Test
    void delivered_delegatesToService() throws Exception
    {
        OrderDeliveredDTO dto = new OrderDeliveredDTO();
        dto.setTraceTime(new Date());
        dto.setContent("已送达");

        mockMvc.perform(post("/agri/seller/order/10/delivered")
                .contentType(MediaType.APPLICATION_JSON)
                .content(objectMapper.writeValueAsString(dto)))
                .andExpect(status().isOk());

        verify(orderService).registerDelivered(eq(101L), eq(10L), any(), eq("seller"));
    }

    @Test
    void remove_delegatesToService() throws Exception
    {
        mockMvc.perform(delete("/agri/seller/order/10"))
                .andExpect(status().isOk());

        verify(orderService).deleteClosedOrder(eq(101L), eq(10L), eq("seller"));
    }

    @Test
    void controller_hasNoCloseEndpoint()
    {
        boolean hasClose = Arrays.stream(SellerOrderController.class.getDeclaredMethods())
                .anyMatch(m -> m.getName().toLowerCase().contains("close"));
        assertFalse(hasClose);
    }
}
