/**
 * Hono 框架 Mock 工厂
 *
 * 提供 Hono Context 和 WebSocket Context 的 mock 实现
 */

import { vi } from 'vitest';

/**
 * 创建 Mock Hono Context
 */
export function createMockHonoContext(options: {
  params?: Record<string, string>;
  body?: unknown;
  query?: Record<string, string>;
  headers?: Record<string, string>;
} = {}) {
  const jsonMock = vi.fn((data: unknown, status?: number) => {
    return new Response(JSON.stringify(data), {
      status: status ?? 200,
      headers: { 'Content-Type': 'application/json' },
    });
  });

  const textMock = vi.fn((text: string, status?: number) => {
    return new Response(text, {
      status: status ?? 200,
      headers: { 'Content-Type': 'text/plain' },
    });
  });

  return {
    req: {
      param: vi.fn((key: string) => options.params?.[key]),
      json: vi.fn().mockResolvedValue(options.body ?? {}),
      query: vi.fn((key: string) => options.query?.[key]),
      header: vi.fn((key: string) => options.headers?.[key.toLowerCase()]),
      url: 'http://localhost:3000/api/test',
      method: 'GET',
      path: '/api/test',
    },
    json: jsonMock,
    text: textMock,
    status: vi.fn().mockReturnThis(),
    header: vi.fn().mockReturnThis(),
    get: vi.fn((key: string) => {
      if (key === 'sessionId') return options.params?.sessionId;
      return undefined;
    }),
    set: vi.fn(),
    // 用于测试验证
    _jsonMock: jsonMock,
    _textMock: textMock,
  };
}

/**
 * 创建 Mock WebSocket Context
 */
export function createMockWSContext() {
  const sendMock = vi.fn();
  const closeMock = vi.fn();

  return {
    send: sendMock,
    close: closeMock,
    readyState: 1, // WebSocket.OPEN
    // 用于测试验证
    _sendMock: sendMock,
    _closeMock: closeMock,
  };
}

/**
 * 创建 Mock SSE Stream
 */
export function createMockSSEStream() {
  const writeMock = vi.fn();
  const closeMock = vi.fn();

  return {
    write: writeMock,
    close: closeMock,
    writeSSE: vi.fn((data: { event?: string; data: string; id?: string }) => {
      writeMock(`event: ${data.event ?? 'message'}\ndata: ${data.data}\n\n`);
    }),
    // 用于测试验证
    _writeMock: writeMock,
    _closeMock: closeMock,
  };
}

/**
 * 创建 Mock Next 函数
 */
export function createMockNext() {
  return vi.fn().mockResolvedValue(undefined);
}
