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

import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.ArgumentMatchers.isNull;
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.HashSet;
import java.util.Set;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.DisplayName;
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.mockito.junit.jupiter.MockitoSettings;
import org.mockito.quality.Strictness;
import org.springframework.http.MediaType;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.github.pagehelper.PageHelper;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.framework.web.exception.GlobalExceptionHandler;
import com.ruoyi.web.modules.diagnosis.VetOnlineConsultTestSamples;
import com.ruoyi.web.modules.diagnosis.domain.BizConsultMessage;
import com.ruoyi.web.modules.diagnosis.domain.VetConsultSendBody;
import com.ruoyi.web.modules.diagnosis.service.IBizVetOnlineConsultService;
import com.ruoyi.web.modules.diagnosis.support.ConsultSessionRules;

@ExtendWith(MockitoExtension.class)
@MockitoSettings(strictness = Strictness.LENIENT)
@DisplayName("在线接诊（兽医）HTTP 接口 MockMvc")
class BizVetOnlineConsultControllerApiTest
{
    private final ObjectMapper objectMapper = new ObjectMapper();

    @Mock
    private IBizVetOnlineConsultService bizVetOnlineConsultService;

    @InjectMocks
    private BizVetOnlineConsultController controller;

    private MockMvc mockMvc;

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

    @AfterEach
    void tearDown()
    {
        SecurityContextHolder.clearContext();
        PageHelper.clearPage();
    }

    private static void loginAsAllPermissions()
    {
        SysUser u = new SysUser();
        u.setUserId(1L);
        u.setUserName("vetTester");
        u.setPassword("x");
        Set<String> perms = new HashSet<>();
        perms.add(Constants.ALL_PERMISSION);
        LoginUser lu = new LoginUser(1L, 100L, u, perms);
        UsernamePasswordAuthenticationToken auth =
                new UsernamePasswordAuthenticationToken(lu, "", lu.getAuthorities());
        SecurityContextHolder.getContext().setAuthentication(auth);
    }

    @Test
    @DisplayName("GET /session/list")
    void list() throws Exception
    {
        when(bizVetOnlineConsultService.selectVetSessionList(any(), eq(1L)))
                .thenReturn(Collections.singletonList(VetOnlineConsultTestSamples.activeSession()));
        mockMvc.perform(get("/diseaseTreatment/onlineConsult/vet/session/list")
                .param("askerName", "扎")
                .param("searchMode", "true"))
                .andExpect(status().isOk())
                .andExpect(jsonPath("$.code").value(200));
    }

    @Test
    @DisplayName("GET /session/{id}/messages")
    void messages() throws Exception
    {
        when(bizVetOnlineConsultService.selectSessionMessages(eq(5001L), isNull(), isNull(), eq(1L)))
                .thenReturn(Collections.singletonList(VetOnlineConsultTestSamples.sampleTextMessage()));
        mockMvc.perform(get("/diseaseTreatment/onlineConsult/vet/session/5001/messages"))
                .andExpect(status().isOk())
                .andExpect(jsonPath("$.code").value(200))
                .andExpect(jsonPath("$.data[0].content").value("牛不吃草"));
    }

    @Test
    @DisplayName("POST /session/{id}/message")
    void send() throws Exception
    {
        BizConsultMessage saved = VetOnlineConsultTestSamples.sampleTextMessage();
        saved.setSenderRole(ConsultSessionRules.SENDER_ROLE_RECEIVER);
        when(bizVetOnlineConsultService.sendVetMessage(eq(5001L), any(), eq(1L), eq("vetTester")))
                .thenReturn(saved);
        VetConsultSendBody body = new VetConsultSendBody();
        body.setMsgType(ConsultSessionRules.MSG_TYPE_TEXT);
        body.setContent("建议隔离");
        mockMvc.perform(post("/diseaseTreatment/onlineConsult/vet/session/5001/message")
                .contentType(MediaType.APPLICATION_JSON)
                .content(objectMapper.writeValueAsString(body)))
                .andExpect(status().isOk())
                .andExpect(jsonPath("$.code").value(200));
    }
}
