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

import static org.junit.jupiter.api.Assertions.assertInstanceOf;
import static org.junit.jupiter.api.Assertions.assertThrows;
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.result.MockMvcResultMatchers.jsonPath;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
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.junit.jupiter.MockitoExtension;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import org.springframework.web.util.NestedServletException;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.web.modules.account.support.MemberContext;
import com.ruoyi.web.modules.entry.constant.MerchantEntryApplyConstants;
import com.ruoyi.web.modules.message.constant.MemberMessageConstants;
import com.ruoyi.web.modules.message.service.IMemberMessageAppService;
import com.ruoyi.web.modules.message.vo.MemberMessageDetailVO;
import com.ruoyi.web.modules.message.vo.MemberMessageListItemVO;
import com.ruoyi.web.modules.message.vo.MemberMessageUnreadVO;

/**
 * C 端站内消息接口测试
 */
@ExtendWith(MockitoExtension.class)
class MemberMessageAppControllerTest
{
    private static final Long MEMBER_ID = 200L;

    private static final Long MESSAGE_ID = 1L;

    @Mock
    private IMemberMessageAppService memberMessageAppService;

    @InjectMocks
    private MemberMessageAppController controller;

    private MockMvc mockMvc;

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

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

    @Test
    void unreadCount_requiresLogin() throws Exception
    {
        NestedServletException ex = assertThrows(NestedServletException.class,
                () -> mockMvc.perform(get("/api/member/message/unread-count")).andReturn());
        assertInstanceOf(ServiceException.class, ex.getCause());
    }

    @Test
    void unreadCount_returns200() throws Exception
    {
        MemberContext.setMemberId(MEMBER_ID);
        MemberMessageUnreadVO vo = new MemberMessageUnreadVO();
        vo.setUnreadCount(2);
        when(memberMessageAppService.getUnreadCount(MEMBER_ID)).thenReturn(vo);

        mockMvc.perform(get("/api/member/message/unread-count"))
                .andExpect(status().isOk())
                .andExpect(jsonPath("$.code").value(200))
                .andExpect(jsonPath("$.data.unreadCount").value(2));

        verify(memberMessageAppService).getUnreadCount(MEMBER_ID);
    }

    @Test
    void list_requiresLogin() throws Exception
    {
        NestedServletException ex = assertThrows(NestedServletException.class,
                () -> mockMvc.perform(get("/api/member/message/list")).andReturn());
        assertInstanceOf(ServiceException.class, ex.getCause());
    }

    @Test
    void list_returns200WithRows() throws Exception
    {
        MemberContext.setMemberId(MEMBER_ID);
        when(memberMessageAppService.listMessages(MEMBER_ID))
                .thenReturn(Collections.singletonList(listItem()));

        mockMvc.perform(get("/api/member/message/list")
                .param("pageNum", "1")
                .param("pageSize", "10"))
                .andExpect(status().isOk())
                .andExpect(jsonPath("$.code").value(200))
                .andExpect(jsonPath("$.rows[0].messageId").value(MESSAGE_ID))
                .andExpect(jsonPath("$.rows[0].title").value(MerchantEntryApplyConstants.MSG_PUBLICITY_TITLE))
                .andExpect(jsonPath("$.rows[0].readFlag").value(MemberMessageConstants.READ_UNREAD))
                .andExpect(jsonPath("$.rows[0].bizType").value(MerchantEntryApplyConstants.BIZ_TYPE_ENTRY_AUDIT));

        verify(memberMessageAppService).listMessages(MEMBER_ID);
    }

    @Test
    void list_emptyResult() throws Exception
    {
        MemberContext.setMemberId(MEMBER_ID);
        when(memberMessageAppService.listMessages(MEMBER_ID)).thenReturn(Collections.emptyList());

        mockMvc.perform(get("/api/member/message/list"))
                .andExpect(status().isOk())
                .andExpect(jsonPath("$.code").value(200))
                .andExpect(jsonPath("$.rows").isArray())
                .andExpect(jsonPath("$.rows").isEmpty());
    }

    @Test
    void detail_requiresLogin() throws Exception
    {
        NestedServletException ex = assertThrows(NestedServletException.class,
                () -> mockMvc.perform(get("/api/member/message/{messageId}", MESSAGE_ID)).andReturn());
        assertInstanceOf(ServiceException.class, ex.getCause());
    }

    @Test
    void detail_returns200() throws Exception
    {
        MemberContext.setMemberId(MEMBER_ID);
        when(memberMessageAppService.getDetailAndMarkRead(MEMBER_ID, MESSAGE_ID)).thenReturn(detail());

        mockMvc.perform(get("/api/member/message/{messageId}", MESSAGE_ID))
                .andExpect(status().isOk())
                .andExpect(jsonPath("$.code").value(200))
                .andExpect(jsonPath("$.data.messageId").value(MESSAGE_ID))
                .andExpect(jsonPath("$.data.readFlag").value(MemberMessageConstants.READ_READ))
                .andExpect(jsonPath("$.data.linkType").value(MemberMessageConstants.LINK_TYPE_MERCHANT_ENTRY))
                .andExpect(jsonPath("$.data.linkAvailable").value(true));

        verify(memberMessageAppService).getDetailAndMarkRead(MEMBER_ID, MESSAGE_ID);
    }

    @Test
    void detail_notFound() throws Exception
    {
        MemberContext.setMemberId(MEMBER_ID);
        when(memberMessageAppService.getDetailAndMarkRead(MEMBER_ID, MESSAGE_ID))
                .thenThrow(new ServiceException(MemberMessageConstants.MSG_NOT_FOUND, 404));

        NestedServletException ex = assertThrows(NestedServletException.class,
                () -> mockMvc.perform(get("/api/member/message/{messageId}", MESSAGE_ID)).andReturn());
        assertInstanceOf(ServiceException.class, ex.getCause());
    }

    private static MemberMessageListItemVO listItem()
    {
        MemberMessageListItemVO vo = new MemberMessageListItemVO();
        vo.setMessageId(MESSAGE_ID);
        vo.setTitle(MerchantEntryApplyConstants.MSG_PUBLICITY_TITLE);
        vo.setSummary("摘要");
        vo.setReadFlag(MemberMessageConstants.READ_UNREAD);
        vo.setCreateTime(new Date());
        vo.setBizType(MerchantEntryApplyConstants.BIZ_TYPE_ENTRY_AUDIT);
        vo.setBizId(50L);
        return vo;
    }

    private static MemberMessageDetailVO detail()
    {
        MemberMessageDetailVO vo = new MemberMessageDetailVO();
        vo.setMessageId(MESSAGE_ID);
        vo.setTitle(MerchantEntryApplyConstants.MSG_PUBLICITY_TITLE);
        vo.setContent("完整正文");
        vo.setReadFlag(MemberMessageConstants.READ_READ);
        vo.setCreateTime(new Date());
        vo.setBizType(MerchantEntryApplyConstants.BIZ_TYPE_ENTRY_AUDIT);
        vo.setBizId(50L);
        vo.setLinkType(MemberMessageConstants.LINK_TYPE_MERCHANT_ENTRY);
        vo.setLinkAvailable(true);
        return vo;
    }
}
