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

import { message } from 'ant-design-vue';

import { requestClient } from '#/api/request';
import { uploadDocumentApi } from '#/api/core/document';

export namespace KnowledgeBaseApi {
  export interface KnowledgeBase {
    id: string;
    name: string;
    description: string | null;
    embeddingModel: string;
    chunkSize: number;
    chunkOverlap: number;
    status: string;
    createdAt: string;
  }

  export interface Document {
    id: string;
    knowledgeBaseId: string;
    title: string;
    fileName: string;
    fileSize: number;
    contentType: string;
    chunkCount: number;
    status: string;
    createdAt: string;
  }
}

export function getKnowledgeBasesApi() {
  return requestClient.get<KnowledgeBaseApi.KnowledgeBase[]>('/knowledge-bases');
}

export function createKnowledgeBaseApi(data: {
  name: string;
  description?: string;
  embeddingModel?: string;
  chunkSize?: number;
  chunkOverlap?: number;
}) {
  return requestClient.post<KnowledgeBaseApi.KnowledgeBase>('/knowledge-bases', data);
}

export function deleteKnowledgeBaseApi(id: string) {
  return requestClient.delete(`/knowledge-bases/${id}`);
}

export function getDocumentsApi(kbId: string) {
  return requestClient.get<KnowledgeBaseApi.Document[]>(
    `/knowledge-bases/${kbId}/documents`,
  );
}

export function uploadDocumentToKbApi(
  kbId: string,
  file: File,
  title?: string,
  onProgress?: (percent: number) => void,
) {
  return uploadDocumentApi(kbId, file, title, onProgress);
}

export function processDocumentApi(docId: string) {
  return requestClient.post(`/documents/${docId}/process`);
}

export namespace ChunkApi {
  export interface ChunkPreview {
    id: string;
    chunkIndex: number;
    content: string;
    tokenCount: number;
    hasEmbedding: boolean;
    embeddingDimension: number | null;
    embeddingPreview: number[] | null;
  }
}

export function getDocumentChunksApi(docId: string) {
  return requestClient.get<ChunkApi.ChunkPreview[]>(`/documents/${docId}/chunks`);
}

/** 上传文件并立即处理 */
export async function uploadAndProcessApi(
  kbId: string,
  file: File,
  title?: string,
  onProgress?: (percent: number) => void,
) {
  const doc = await uploadDocumentToKbApi(kbId, file, title, onProgress);
  const docId = (doc as any).id;
  if (docId) {
    message.loading({ content: '正在处理文档...', key: 'process', duration: 0 });
    try {
      await processDocumentApi(docId);
      message.success({ content: '文档处理完成', key: 'process' });
    } catch {
      message.error({ content: '文档处理失败', key: 'process' });
    }
  }
  return doc;
}
