// @vitest-environment happy-dom

import { createPinia, setActivePinia } from 'pinia';
import { beforeEach, describe, expect, it, vi } from 'vitest';

import { useUserStore } from '@easyflow/stores';

import { clearAgentChatBrowserCache } from '#/utils/agent-chat-cache';

import { sendAgentChat } from './api';
import { agentChatRuntimeManager } from './agentChatRuntimeManager';

vi.mock('./api', () => ({
  generateAgentSessionId: vi.fn(),
  sendAgentChat: vi.fn(),
  stopAgentChatStream: vi.fn(),
}));

describe('agentChatRuntimeManager', () => {
  beforeEach(() => {
    setActivePinia(createPinia());
    sessionStorage.clear();
    vi.clearAllMocks();
  });

  it('replaces draft image URLs and isolates snapshots by account', async () => {
    let callbacks: any;
    vi.mocked(sendAgentChat).mockImplementation((_data, options) => {
      callbacks = options;
      return Promise.resolve() as any;
    });
    const userStore = useUserStore();
    const firstAccount = {
      avatar: '',
      id: 'user-1',
      loginName: 'admin',
      nickname: '管理员',
      tenantId: 'tenant-1',
    };
    userStore.setUserInfo(firstAccount);

    await agentChatRuntimeManager.start({
      agentId: 'agent-1',
      images: [
        {
          name: 'draft.png',
          previewUrl: '/api/v1/agent/media/content?reference=draft%3Aupload-1',
          status: 'ready',
          uploadId: 'upload-1',
        },
      ],
      prompt: '识别图片',
      sessionId: '101',
    });
    callbacks.onMessage({
      data: JSON.stringify({
        domain: 'SYSTEM',
        payload: {
          images: [
            {
              imageRef: 'formal:101:201:0:png',
              name: 'draft.png',
              previewUrl:
                '/api/v1/agent/media/content?reference=formal:101:201:0:png',
            },
          ],
        },
        type: 'INPUT_ACCEPTED',
      }),
    });

    const accepted = agentChatRuntimeManager.getSnapshot('101');
    const userMessage = accepted?.items.find(
      (item) => item.type === 'message' && item.role === 'user',
    );
    expect(
      userMessage?.type === 'message' ? userMessage.images?.[0] : null,
    ).toEqual(
      expect.objectContaining({
        imageRef: 'formal:101:201:0:png',
        previewUrl:
          '/api/v1/agent/media/content?reference=formal:101:201:0:png',
      }),
    );

    userStore.setUserInfo({
      ...firstAccount,
      id: 'user-2',
      loginName: 'other',
      nickname: '其他用户',
    });
    expect(agentChatRuntimeManager.getSnapshot('101')).toBeUndefined();

    clearAgentChatBrowserCache(firstAccount);
    userStore.setUserInfo(firstAccount);
    expect(agentChatRuntimeManager.getSnapshot('101')).toBeUndefined();
  });
});
