import { useEventCallback } from "../../../_vendor/usehooks-ts/dist-index.js";
function useFileUploadHandler(options) {
  const {
    onFileUpload,
    onFileUploadError,
    updateAttachmentProgress,
    setAttachmentError,
    updateAttachmentUrl,
    updateAttachmentExtraData,
    setAttachmentUploading,
    getFileById,
    createAbortController,
    cleanupAbortController
  } = options;
  const CONCURRENT_UPLOAD_LIMIT = 3;
  const uploadSingleFile = useEventCallback(async (file) => {
    const abortController = createAbortController(file.id);
    setAttachmentUploading(file.id);
    try {
      const fileObject = getFileById(file.id);
      if (!fileObject) {
        throw new Error("File object not found");
      }
      if (!onFileUpload) {
        throw new Error("Upload function not provided");
      }
      const uploaded = await onFileUpload(fileObject, {
        onProgress: (progress) => {
          if (abortController.signal.aborted) {
            return;
          }
          updateAttachmentProgress(file.id, progress.progress || progress.percentage || 0);
        },
        signal: abortController.signal
        // 传递取消信号
      });
      if (abortController.signal.aborted) {
        return;
      }
      updateAttachmentUrl(file.id, uploaded.url);
      if (uploaded.extraData) {
        options.updateAttachmentExtraData(file.id, uploaded.extraData);
      }
      cleanupAbortController(file.id);
    } catch (error) {
      if (error instanceof Error && error.name === "AbortError") {
        return;
      }
      setAttachmentError(file.id, error instanceof Error ? error.message : "Upload failed");
      cleanupAbortController(file.id);
    }
  });
  const handleFilesUpload = useEventCallback(async (files) => {
    if (!onFileUpload) {
      return;
    }
    const uploadQueue = [...files];
    const activeUploads = /* @__PURE__ */ new Set();
    const processQueue = async () => {
      while (uploadQueue.length > 0 && activeUploads.size < CONCURRENT_UPLOAD_LIMIT) {
        const file = uploadQueue.shift();
        activeUploads.add(file.id);
        uploadSingleFile(file).catch(() => {
        }).finally(() => {
          activeUploads.delete(file.id);
          processQueue();
        });
      }
    };
    await processQueue();
  });
  return {
    handleFilesUpload,
    uploadSingleFile
  };
}
export {
  useFileUploadHandler
};
//# sourceMappingURL=use-file-upload-handler.js.map
