import { MEDIA_SERVICES_URL } from "./consts.js";
const createUploadFn = (services) => {
  const consumer = services.editorProps.biSettings?.consumer;
  const { uid, siteOwnerId, getWixClientPromise } = services.wixInstance();
  const folderId = getFolderId(uid, siteOwnerId, services.editorProps.visitorUploads);
  return async (file, type, options) => {
    const { privacy = "public", onUploadProgress } = options || {};
    const params = new URLSearchParams({ mediaType: type, privacy });
    const wixClient = await getWixClientPromise();
    const response = await wixClient.fetchWithAuth(
      `${MEDIA_SERVICES_URL}/upload-url?${params.toString()}`,
      { method: "POST", body: JSON.stringify({}) }
    );
    const responseData = await response.json();
    const uploadUrl = responseData.uploadUrl;
    const formData = new FormData();
    formData.append("file", file, file.name);
    formData.append("media_type", type);
    formData.append("acl", privacy);
    if (consumer) {
      formData.append("tags", `rich_content_${consumer}`);
    }
    if (folderId) {
      formData.append("parent_folder_id", folderId);
    }
    const requestConfig = {
      onUploadProgress: (progressEvent) => {
        onUploadProgress?.(progressEvent);
      }
    };
    const uploadResponse = await wixClient.fetchWithAuth(uploadUrl, {
      method: "POST",
      body: formData,
      ...requestConfig
    });
    const uploadRepsonseJson = await uploadResponse.json();
    const { error_description } = uploadRepsonseJson;
    return new Promise(
      (resolve, reject) => error_description ? reject(uploadRepsonseJson) : resolve(uploadRepsonseJson[0])
    );
  };
};
const getFolderId = (userId, siteOwnerId, visitorUploads) => {
  const isOwner = siteOwnerId === userId;
  const { folderId, shouldIncludeSiteOwner } = visitorUploads || {};
  const shouldUploadToFolder = shouldIncludeSiteOwner || !isOwner;
  return shouldUploadToFolder ? folderId : null;
};
export {
  createUploadFn
};
//# sourceMappingURL=media-manager-uploader.js.map
