/**
 * @description 消息相关API
 * @author yslg
 * @since 2025-10-15
 */

import { api } from '@/apis/index';
import type { AiMessage, ChatRequest, ChatResponse, ResultDomain } from '@/types';

/**
 * 消息API服务
 */
export const messageApi = {
  /**
   * 获取对话消息列表
   * @param conversationID 对话ID
   * @returns Promise<ResultDomain<AiMessage>>
   */
  async getMessageList(conversationID: string): Promise<ResultDomain<AiMessage>> {
    const response = await api.get<AiMessage>(`/ai/message/list`, { conversationID });
    return response.data;
  },

  /**
   * 发送消息
   * @param request 消息请求
   * @returns Promise<ResultDomain<ChatResponse>>
   */
  async sendMessage(request: ChatRequest): Promise<ResultDomain<ChatResponse>> {
    const response = await api.post<ChatResponse>('/ai/message/send', request);
    return response.data;
  }

  /**
   * 流式发送消息
   * @param request 消息请求
   * @param onMessage 消息回调
   * @returns Promise<void>
   */
  // async sendMessageStream(request: ChatRequest, onMessage: (message: string) => void): Promise<void> {
  //   const response = await api.post('/ai/message/stream', { ...request, stream: true }, {
  //     responseType: 'stream'
  //   });
    
  //   // 处理流式响应
  //   const reader = response.data.getReader();
  //   const decoder = new TextDecoder();
  //   let done = false;

  //   while (!done) {
  //     const readResult = await reader.read();
  //     done = readResult.done;
  //     if (done) break;

  //     const chunk = decoder.decode(readResult.value);
  //     const lines = chunk.split('\n');
      
  //     for (const line of lines) {
  //       if (line.startsWith('data: ')) {
  //         const data = line.slice(6);
  //         if (data === '[DONE]') return;
          
  //         try {
  //           const parsed = JSON.parse(data);
  //           onMessage(parsed.content || '');
  //         } catch (e) {
  //           console.error('解析流式数据失败:', e);
  //         }
  //       }
  //     }
  //   }
  // }
};
