package com.ruoyi.web.modules.order.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.verify;
import static org.mockito.Mockito.when;
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 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.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.account.support.MemberContext;
import com.ruoyi.web.modules.order.constant.CheckoutConstants;
import com.ruoyi.web.modules.order.constant.OrderConstants;
import com.ruoyi.web.modules.order.dto.CheckoutLineDTO;
import com.ruoyi.web.modules.order.dto.CheckoutPreviewDTO;
import com.ruoyi.web.modules.order.dto.CheckoutSubmitDTO;
import com.ruoyi.web.modules.order.service.ICheckoutAppService;
import com.ruoyi.web.modules.order.vo.CheckoutPreviewVO;
import com.ruoyi.web.modules.order.vo.CheckoutSubmitResultVO;

@ExtendWith(MockitoExtension.class)
class CheckoutAppControllerTest
{
    private static final Long MEMBER_ID = 200L;

    @Mock
    private ICheckoutAppService checkoutAppService;

    @InjectMocks
    private CheckoutAppController controller;

    private MockMvc mockMvc;

    private ObjectMapper objectMapper;

    @BeforeEach
    void setUp()
    {
        mockMvc = MockMvcBuilders.standaloneSetup(controller).build();
        objectMapper = new ObjectMapper();
    }

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

    @Test
    void preview_requiresLogin() throws Exception
    {
        CheckoutPreviewDTO dto = new CheckoutPreviewDTO();
        dto.setSource(CheckoutConstants.SOURCE_CART);
        NestedServletException ex = assertThrows(NestedServletException.class,
                () -> mockMvc.perform(post("/api/checkout/preview")
                        .contentType(MediaType.APPLICATION_JSON)
                        .content(objectMapper.writeValueAsString(dto))).andReturn());
        assertInstanceOf(ServiceException.class, ex.getCause());
    }

    @Test
    void preview_buyNow_returns200() throws Exception
    {
        MemberContext.setMemberId(MEMBER_ID);
        CheckoutPreviewVO vo = new CheckoutPreviewVO();
        vo.setGoodsAmount(new BigDecimal("10.00"));
        vo.setFreightAmount(new BigDecimal("8.00"));
        vo.setPayAmount(new BigDecimal("18.00"));
        when(checkoutAppService.preview(eq(MEMBER_ID), any(CheckoutPreviewDTO.class))).thenReturn(vo);

        CheckoutPreviewDTO dto = new CheckoutPreviewDTO();
        dto.setSource(CheckoutConstants.SOURCE_BUY_NOW);
        CheckoutLineDTO line = new CheckoutLineDTO();
        line.setGoodsId(1L);
        line.setQuantity(1);
        dto.setItems(java.util.Collections.singletonList(line));

        mockMvc.perform(post("/api/checkout/preview")
                .contentType(MediaType.APPLICATION_JSON)
                .content(objectMapper.writeValueAsString(dto)))
                .andExpect(status().isOk())
                .andExpect(jsonPath("$.code").value(200))
                .andExpect(jsonPath("$.data.payAmount").value(18.00));
    }

    @Test
    void submit_buyNow_returns200() throws Exception
    {
        MemberContext.setMemberId(MEMBER_ID);
        when(checkoutAppService.submit(eq(MEMBER_ID), any(CheckoutSubmitDTO.class)))
                .thenReturn(new CheckoutSubmitResultVO(900L, "O20260526000001", new BigDecimal("18.00"), null));

        CheckoutSubmitDTO dto = new CheckoutSubmitDTO();
        dto.setSource(CheckoutConstants.SOURCE_BUY_NOW);
        dto.setAddressId(5L);
        dto.setPayType(OrderConstants.PAY_TYPE_WECHAT);
        CheckoutLineDTO line = new CheckoutLineDTO();
        line.setGoodsId(1L);
        line.setQuantity(1);
        dto.setItems(java.util.Collections.singletonList(line));

        mockMvc.perform(post("/api/checkout/submit")
                .contentType(MediaType.APPLICATION_JSON)
                .content(objectMapper.writeValueAsString(dto)))
                .andExpect(status().isOk())
                .andExpect(jsonPath("$.data.orderId").value(900));
    }

    @Test
    void preview_returns200() throws Exception
    {
        MemberContext.setMemberId(MEMBER_ID);
        CheckoutPreviewVO vo = new CheckoutPreviewVO();
        vo.setGoodsAmount(new BigDecimal("20.00"));
        vo.setFreightAmount(new BigDecimal("5.00"));
        vo.setPayAmount(new BigDecimal("25.00"));
        when(checkoutAppService.preview(eq(MEMBER_ID), any(CheckoutPreviewDTO.class))).thenReturn(vo);

        CheckoutPreviewDTO dto = new CheckoutPreviewDTO();
        dto.setSource(CheckoutConstants.SOURCE_CART);

        mockMvc.perform(post("/api/checkout/preview")
                .contentType(MediaType.APPLICATION_JSON)
                .content(objectMapper.writeValueAsString(dto)))
                .andExpect(status().isOk())
                .andExpect(jsonPath("$.code").value(200))
                .andExpect(jsonPath("$.data.payAmount").value(25.00));

        verify(checkoutAppService).preview(eq(MEMBER_ID), any(CheckoutPreviewDTO.class));
    }

    @Test
    void submit_returns200() throws Exception
    {
        MemberContext.setMemberId(MEMBER_ID);
        when(checkoutAppService.submit(eq(MEMBER_ID), any(CheckoutSubmitDTO.class)))
                .thenReturn(new CheckoutSubmitResultVO(900L, "O20260526000001", new BigDecimal("25.00"), null));

        CheckoutSubmitDTO dto = new CheckoutSubmitDTO();
        dto.setSource(CheckoutConstants.SOURCE_CART);
        dto.setAddressId(5L);
        dto.setPayType(OrderConstants.PAY_TYPE_WECHAT);

        mockMvc.perform(post("/api/checkout/submit")
                .contentType(MediaType.APPLICATION_JSON)
                .content(objectMapper.writeValueAsString(dto)))
                .andExpect(status().isOk())
                .andExpect(jsonPath("$.data.orderId").value(900));
    }
}
