jest.mock('uuid', () => ({
  v4: jest.fn(() => 'session-id'),
}));

import { NetaClawAgentExecutorService } from '../src/modules/netaclaw/service/agent_executor.js';

describe('NetaClawAgentExecutorService session-tree routing', () => {
  it('routes agent-backed chat requests through executeSessionTreeChat instead of the legacy executeChat path', async () => {
    const service = new NetaClawAgentExecutorService();

    service.sessionService = {} as any;
    service.agentService = {
      info: jest.fn().mockResolvedValue({
        id: 7,
        name: 'default',
        systemPrompt: 'You are the runtime.',
        skills: [],
        config: {},
        modelConfig: {},
        subagentConfig: {},
      }),
      agentRepo: {
        findOneBy: jest.fn(),
      },
    } as any;
    service.skillLoader = {} as any;
    service.channelService = {
      resolveForAgent: jest.fn(),
    } as any;
    service.toolResolver = {
      resolve: jest.fn().mockResolvedValue({
        tools: [],
        toolNames: [],
        toolPromptHints: {},
        builtinToolNames: [],
        disabledReasons: [],
      }),
    } as any;
    service.chatOrchestrator = {
      executeSessionTreeChat: jest.fn().mockResolvedValue({
        sessionId: 'session-tree-1',
        finalContent: 'final answer',
        content: 'final answer',
        usage: { inputTokens: 12, outputTokens: 5 },
        toolCallCount: 0,
        assistantEntryId: 'entry_assistant_1',
        subagentBatches: [],
      }),
      executeChat: jest.fn(),
    } as any;
    service.subagentService = {} as any;
    service.memoryRepo = {} as any;
    (service as any).agentRunner = jest.fn();

    const result = await service.execute({
      sessionId: 'session-tree-1',
      message: 'hello tree',
      agentId: 7,
      userId: 'user-1',
    });

    expect(service.chatOrchestrator.executeSessionTreeChat).toHaveBeenCalledWith(
      expect.objectContaining({
        sessionId: 'session-tree-1',
        requestedAgentName: 'default',
        message: 'hello tree',
        agentId: 7,
        userId: 'user-1',
        runner: expect.any(Function),
      })
    );
    expect(service.chatOrchestrator.executeChat).not.toHaveBeenCalled();
    expect(result).toEqual({
      sessionId: 'session-tree-1',
      content: 'final answer',
      usage: { inputTokens: 12, outputTokens: 5 },
      toolCallCount: 0,
      agentId: 7,
      agentName: 'default',
      assistantEntryId: 'entry_assistant_1',
      subagentBatches: [],
    });
  });
});
