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.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.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.delivery.service.IShopDeliveryService;
import com.ruoyi.web.modules.delivery.vo.DeliveryRegionVO;
import com.ruoyi.web.modules.delivery.vo.ShopDeliverySettingVO;
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;
import com.ruoyi.web.modules.order.vo.SellerShipBadgeVO;

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

    @Mock
    private IShopDeliveryService shopDeliveryService;

    @Spy
    @InjectMocks
    private SellerShipController 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 badges_withoutShopId_rejected()
    {
        SellerShopContext.clear();

        NestedServletException ex = assertThrows(NestedServletException.class,
                () -> mockMvc.perform(get("/agri/seller/ship/badges")).andReturn());
        assertInstanceOf(ServiceException.class, ex.getCause());
        verify(orderService, never()).countSellerShipBadges(any());
    }

    @Test
    void badges_returns200() throws Exception
    {
        SellerShipBadgeVO badges = new SellerShipBadgeVO();
        badges.setPendingShipCount(3);
        badges.setShippedCount(2);
        badges.setCompletedCount(10);
        when(orderService.countSellerShipBadges(101L)).thenReturn(badges);

        mockMvc.perform(get("/agri/seller/ship/badges"))
                .andExpect(status().isOk())
                .andExpect(jsonPath("$.code").value(200))
                .andExpect(jsonPath("$.data.pendingShipCount").value(3))
                .andExpect(jsonPath("$.data.shippedCount").value(2))
                .andExpect(jsonPath("$.data.completedCount").value(10));
    }

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

        NestedServletException ex = assertThrows(NestedServletException.class,
                () -> mockMvc.perform(get("/agri/seller/ship/list").param("orderStatus", "1")).andReturn());
        assertInstanceOf(ServiceException.class, ex.getCause());
        verify(orderService, never()).selectSellerList(any(), any());
    }

    @Test
    void list_rejectsInvalidOrderStatus()
    {
        NestedServletException ex = assertThrows(NestedServletException.class,
                () -> mockMvc.perform(get("/agri/seller/ship/list").param("orderStatus", "0")).andReturn());
        assertInstanceOf(ServiceException.class, ex.getCause());
        verify(orderService, never()).selectSellerList(any(), any());
    }

    @Test
    void list_rejectsMissingOrderStatus()
    {
        NestedServletException ex = assertThrows(NestedServletException.class,
                () -> mockMvc.perform(get("/agri/seller/ship/list")).andReturn());
        assertInstanceOf(ServiceException.class, ex.getCause());
        verify(orderService, never()).selectSellerList(any(), any());
    }

    @Test
    void list_returns200ForPendingShip() 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/ship/list").param("orderStatus", "1"))
                .andExpect(status().isOk())
                .andExpect(jsonPath("$.code").value(200))
                .andExpect(jsonPath("$.rows[0].orderNo").value("O202605260001"));
    }

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

        ShopDeliverySettingVO delivery = new ShopDeliverySettingVO();
        delivery.setShipperName("张三");
        DeliveryRegionVO region = new DeliveryRegionVO();
        region.setCityName("拉萨市");
        delivery.setRegion(region);
        when(shopDeliveryService.getByShopId(101L)).thenReturn(delivery);

        mockMvc.perform(get("/agri/seller/ship/10"))
                .andExpect(status().isOk())
                .andExpect(jsonPath("$.data.orderNo").value("O202605260001"))
                .andExpect(jsonPath("$.data.shopDelivery.shipperName").value("张三"))
                .andExpect(jsonPath("$.data.shopDelivery.region.cityName").value("拉萨市"));
    }

    @Test
    void detail_withoutConfiguredDelivery_stillReturns200() throws Exception
    {
        OrderDetailVO vo = new OrderDetailVO();
        vo.setOrderId(10L);
        vo.setOrderNo("O202605260001");
        when(orderService.selectSellerShipDetail(101L, 10L)).thenReturn(vo);
        when(shopDeliveryService.getByShopId(101L)).thenReturn(null);

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

    @Test
    void ship_delegatesToServiceWithoutDelivery() 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/ship/10/ship")
                .contentType(MediaType.APPLICATION_JSON)
                .content(objectMapper.writeValueAsString(dto)))
                .andExpect(status().isOk());

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

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

        mockMvc.perform(post("/agri/seller/ship/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/ship/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 controller_hasNoDeleteEndpoint()
    {
        boolean hasDelete = Arrays.stream(SellerShipController.class.getDeclaredMethods())
                .anyMatch(m -> m.getName().equals("remove") || m.getName().equals("delete"));
        assertFalse(hasDelete);
    }
}
