import { useAccessStore } from '@vben/stores';

import { requestClient } from '#/api/request';

export namespace AiChatApi {
  export interface Conversation {
    id: string;
    title: string;
    userId: string;
    knowledgeBaseId: string | null;
    createdAt: string;
  }

  export interface Message {
    id: string;
    role: string;
    content: string;
    tokenUsage: number | null;
    createdAt: string;
  }

  export interface ConversationDetail {
    id: string;
    title: string;
    userId: string;
    knowledgeBaseId: string | null;
    createdAt: string;
    messages: Message[];
  }

  export interface SendMessageResponse {
    messageId: string;
    content: string;
  }
}

export function getConversationsApi() {
  return requestClient.get<AiChatApi.Conversation[]>('/chat/conversations');
}

export function createConversationApi(data: { title: string }) {
  return requestClient.post<AiChatApi.Conversation>(
    '/chat/conversations',
    data,
  );
}

export function deleteConversationApi(id: string) {
  return requestClient.delete(`/chat/conversations/${id}`);
}

export function getConversationDetailApi(id: string) {
  return requestClient.get<AiChatApi.ConversationDetail>(
    `/chat/conversations/${id}`,
  );
}

export function sendMessageApi(
  conversationId: string,
  data: { content: string },
) {
  return requestClient.post<AiChatApi.SendMessageResponse>(
    `/chat/conversations/${conversationId}/messages`,
    data,
  );
}

export function streamMessageApi(
  conversationId: string,
  content: string,
): Promise<ReadableStream<Uint8Array>> {
  const accessStore = useAccessStore();
  return fetch(
    `${import.meta.env.VITE_GLOB_API_URL || '/api'}/chat/conversations/${conversationId}/stream`,
    {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        Authorization: `Bearer ${accessStore.accessToken}`,
      },
      body: JSON.stringify({ content }),
    },
  ).then((res) => {
    if (!res.ok) throw new Error(`HTTP ${res.status}`);
    return res.body!;
  });
}
