package tech.easyflow.agent.runtime.agui;

import org.junit.Test;
import org.springframework.web.servlet.mvc.method.annotation.SseEmitter;

import java.util.List;

import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;

/**
 * AG-UI 重连订阅共享调度测试。
 */
public class AgentAguiRunSubscriptionServiceTest {

    /**
     * 验证同一 run 的不同游标独立读取窗口，尾部实时订阅不受历史回放阻塞。
     *
     * @throws Exception SSE mock 发送异常
     */
    @Test
    public void shouldDispatchDistinctCursorWindowsIndependently() throws Exception {
        AgentAguiRunStore store = mock(AgentAguiRunStore.class);
        AgentAguiRunSubscriptionService service = new AgentAguiRunSubscriptionService(store);
        AgentAguiRunDescriptor descriptor = new AgentAguiRunDescriptor(
                "run-1", "request-1", "thread-1", "agent-1", "session-1",
                "user-1", "tenant-1", false, AgentAguiRunStatus.RUNNING,
                1000L, 1L, 2L);
        SseEmitter fromStart = mock(SseEmitter.class);
        SseEmitter fromTail = mock(SseEmitter.class);
        service.subscribe(descriptor, 0L, fromStart);
        service.subscribe(descriptor, 999L, fromTail);
        when(store.readAfter("run-1", 0L)).thenReturn(java.util.Collections.nCopies(
                256, "{\"type\":\"TEXT_MESSAGE_CONTENT\"}"));
        when(store.readAfter("run-1", 999L)).thenReturn(List.of(
                "{\"type\":\"TEXT_MESSAGE_CONTENT\",\"delta\":\"tail\"}"));
        when(store.find("run-1")).thenReturn(descriptor);

        service.dispatch();

        verify(store).readAfter("run-1", 0L);
        verify(store).readAfter("run-1", 999L);
        verify(store).find("run-1");
        verify(fromStart, times(256)).send(any(SseEmitter.SseEventBuilder.class));
        verify(fromTail).send(any(SseEmitter.SseEventBuilder.class));
    }
}
