package com.gxwebsoft.house.controller;

import com.gxwebsoft.common.core.web.ApiResult;
import com.gxwebsoft.common.core.websocket.WebSocketServer;
import com.gxwebsoft.common.system.entity.User;
import com.gxwebsoft.house.entity.HouseAiChatRequest;
import com.gxwebsoft.house.entity.HouseAiChatResponse;
import com.gxwebsoft.house.service.HouseAiChatService;
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.Mock;
import org.mockito.junit.jupiter.MockitoExtension;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.test.util.ReflectionTestUtils;

import java.io.IOException;

import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.contains;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.doThrow;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;

@ExtendWith(MockitoExtension.class)
class HouseAiChatControllerTest {

    @Mock
    private HouseAiChatService houseAiChatService;
    @Mock
    private WebSocketServer webSocketServer;

    private HouseAiChatController controller;

    @BeforeEach
    void setUp() {
        controller = new HouseAiChatController();
        ReflectionTestUtils.setField(controller, "houseAiChatService", houseAiChatService);
        ReflectionTestUtils.setField(controller, "webSocketServer", webSocketServer);

        User user = new User();
        user.setUserId(1001);
        user.setTenantId(2001);
        SecurityContextHolder.getContext().setAuthentication(new UsernamePasswordAuthenticationToken(user, null));
    }

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

    @Test
    void progressWebSocketFailureDoesNotFailAiRequest() throws Exception {
        HouseAiChatResponse response = new HouseAiChatResponse();
        response.setAnswer("已找到房源");
        when(houseAiChatService.answer(any(HouseAiChatRequest.class))).thenReturn(response);
        doThrow(new IOException("WebSocket disconnected"))
            .when(webSocketServer).sendMessage(eq("1001"), contains("house_ai_progress"));

        ApiResult<?> result = controller.message(request());

        assertEquals("处理成功", result.getMessage());
        assertEquals(response, result.getData());
        verify(houseAiChatService).answer(any(HouseAiChatRequest.class));
    }

    private HouseAiChatRequest request() {
        HouseAiChatRequest request = new HouseAiChatRequest();
        request.setQuestion("南宁青秀区租房");
        request.setConversationId("conversation-1");
        return request;
    }
}
