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

import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.eq;
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.AiOnlineConsultTestSamples;
import com.ruoyi.web.modules.diagnosis.domain.AiConsultSendResult;
import com.ruoyi.web.modules.diagnosis.domain.AiConsultSessionView;
import com.ruoyi.web.modules.diagnosis.domain.BizConsultMessage;
import com.ruoyi.web.modules.diagnosis.domain.VetConsultSendBody;
import com.ruoyi.web.modules.diagnosis.service.IBizAiOnlineConsultService;
import com.ruoyi.web.modules.diagnosis.support.AiConsultConstants;
import com.ruoyi.web.modules.diagnosis.support.ConsultSessionRules;

@ExtendWith(MockitoExtension.class)
@MockitoSettings(strictness = Strictness.LENIENT)
@DisplayName("AI诊断后台 HTTP MockMvc")
class BizAiOnlineConsultControllerApiTest
{
    private final ObjectMapper objectMapper = new ObjectMapper();

    @Mock
    private IBizAiOnlineConsultService bizAiOnlineConsultService;

    @InjectMocks
    private BizAiOnlineConsultController 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("aiTester");
        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 含 disclaimer")
    void listWithDisclaimer() throws Exception
    {
        when(bizAiOnlineConsultService.selectAiSessionList(any(), eq(1L)))
                .thenReturn(Collections.singletonList(AiOnlineConsultTestSamples.activeAiSession()));
        mockMvc.perform(get("/diseaseTreatment/onlineConsult/ai/session/list"))
                .andExpect(status().isOk())
                .andExpect(jsonPath("$.code").value(200))
                .andExpect(jsonPath("$.disclaimer").value(AiConsultConstants.DISCLAIMER));
    }

    @Test
    @DisplayName("POST /session")
    void createSession() throws Exception
    {
        AiConsultSessionView view = new AiConsultSessionView();
        view.setId(AiOnlineConsultTestSamples.SESSION_ID);
        view.setDisclaimer(AiConsultConstants.DISCLAIMER);
        when(bizAiOnlineConsultService.createAiSession(eq(1L), any(), any())).thenReturn(view);
        mockMvc.perform(post("/diseaseTreatment/onlineConsult/ai/session")
                .contentType(MediaType.APPLICATION_JSON)
                .content("{}"))
                .andExpect(status().isOk())
                .andExpect(jsonPath("$.code").value(200))
                .andExpect(jsonPath("$.data.disclaimer").value(AiConsultConstants.DISCLAIMER));
    }

    @Test
    @DisplayName("POST /session/{id}/message")
    void sendMessage() throws Exception
    {
        BizConsultMessage user = AiOnlineConsultTestSamples.sampleTextMessage();
        BizConsultMessage ai = new BizConsultMessage();
        ai.setSenderRole(ConsultSessionRules.SENDER_ROLE_AI);
        ai.setContent("AI回复");
        AiConsultSendResult result = new AiConsultSendResult();
        result.setUserMessage(user);
        result.setAiMessage(ai);
        when(bizAiOnlineConsultService.sendAiMessage(eq(AiOnlineConsultTestSamples.SESSION_ID), any(), eq(1L), any(),
                any()))
                .thenReturn(result);
        VetConsultSendBody body = new VetConsultSendBody();
        body.setMsgType(ConsultSessionRules.MSG_TYPE_TEXT);
        body.setContent("牛不吃草");
        mockMvc.perform(post("/diseaseTreatment/onlineConsult/ai/session/" + AiOnlineConsultTestSamples.SESSION_ID
                + "/message")
                .contentType(MediaType.APPLICATION_JSON)
                .content(objectMapper.writeValueAsString(body)))
                .andExpect(status().isOk())
                .andExpect(jsonPath("$.data.aiMessage.senderRole").value(3));
    }

    @Test
    @DisplayName("POST /session/{id}/hide 管理端隐藏会话")
    void hideSession() throws Exception
    {
        when(bizAiOnlineConsultService.hideSession(AiOnlineConsultTestSamples.SESSION_ID, 1L)).thenReturn(1);
        mockMvc.perform(post("/diseaseTreatment/onlineConsult/ai/session/"
                + AiOnlineConsultTestSamples.SESSION_ID + "/hide"))
                .andExpect(status().isOk())
                .andExpect(jsonPath("$.code").value(200));
    }
}
