package com.ruoyi.web.kb.support;

import static org.junit.jupiter.api.Assertions.assertTrue;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.nio.charset.StandardCharsets;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
import org.springframework.http.MediaType;
import org.springframework.mock.web.MockHttpServletResponse;

@DisplayName("SseStreamSupport")
class SseStreamSupportTest
{
    @Test
    @DisplayName("SSE 响应头")
    void prepareSseResponse() throws Exception
    {
        MockHttpServletResponse response = new MockHttpServletResponse();
        SseStreamSupport.prepareSseResponse(response);
        assertTrue(response.getContentType().startsWith(MediaType.TEXT_EVENT_STREAM_VALUE));
        assertTrue("no".equals(response.getHeader("X-Accel-Buffering")));
    }

    @Test
    @DisplayName("pipeWithFlush 透传")
    void pipeWithFlush() throws Exception
    {
        byte[] payload = "data: {\"x\":1}\n\n".getBytes(StandardCharsets.UTF_8);
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        SseStreamSupport.pipeWithFlush(new ByteArrayInputStream(payload), out);
        assertTrue(out.toString(StandardCharsets.UTF_8.name()).contains("data:"));
    }

    @Test
    @DisplayName("writeDataEvent")
    void writeDataEvent() throws Exception
    {
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        SseStreamSupport.writeDataEvent(out, "[DONE]");
        assertTrue(out.toString(StandardCharsets.UTF_8.name()).contains("data: [DONE]"));
    }
}
