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

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

export interface ChunkUploadSession {
  sessionId: string;
  knowledgeBaseId: string;
  fileName: string;
  fileSize: number;
  chunkCount: number;
}

/** 分片上传阈值：5MB 以上自动分片 */
const CHUNK_THRESHOLD = 5 * 1024 * 1024;
const CHUNK_SIZE = 2 * 1024 * 1024; // 每片 2MB

/** 上传文档（自动判断是否分片） */
export async function uploadDocumentApi(
  knowledgeBaseId: string,
  file: File,
  title?: string,
  onProgress?: (percent: number) => void,
) {
  if (file.size > CHUNK_THRESHOLD) {
    return uploadDocumentChunked(knowledgeBaseId, file, title, onProgress);
  }
  // 小文件直接上传
  const formData = new FormData();
  formData.append('file', file);
  if (title) formData.append('Title', title);
  return requestClient.post(
    `/knowledge-bases/${knowledgeBaseId}/documents`,
    formData,
  );
}

async function uploadDocumentChunked(
  knowledgeBaseId: string,
  file: File,
  title?: string,
  onProgress?: (percent: number) => void,
) {
  const chunkCount = Math.ceil(file.size / CHUNK_SIZE);

  // 1. 初始化
  const session = await requestClient.post<ChunkUploadSession>(
    `/knowledge-bases/${knowledgeBaseId}/documents/chunk-upload/init`,
    { fileName: file.name, fileSize: file.size, chunkCount },
  );

  // 2. 逐片上传
  for (let i = 0; i < chunkCount; i++) {
    const start = i * CHUNK_SIZE;
    const end = Math.min(start + CHUNK_SIZE, file.size);
    const blob = file.slice(start, end);

    const formData = new FormData();
    formData.append('file', blob, file.name);

    const accessStore = useAccessStore();
    await fetch(
      `${import.meta.env.VITE_GLOB_API_URL || '/api'}/documents/chunk-upload/${session.sessionId}/chunks/${i}`,
      {
        method: 'POST',
        headers: { Authorization: `Bearer ${accessStore.accessToken}` },
        body: formData,
      },
    );

    onProgress?.(Math.round(((i + 1) / chunkCount) * 100));
  }

  // 3. 合并完成
  return requestClient.post(
    `/documents/chunk-upload/${session.sessionId}/complete`,
    { title: title || file.name },
  );
}
