import { useCallback as m } from "react";
import { useShopActions as c } from "../../internal/useShopActions.js";
import { fileToDataUri as u } from "../../utils/image.js";
const d = async (e) => {
  const r = await u(e), o = await (await fetch(r)).blob();
  return {
    mimeType: e.type,
    fileSize: e.size ?? o.size,
    fileBlob: o
  };
}, f = async (e, r) => {
  const t = new FormData();
  r.parameters.forEach(({ name: s, value: a }) => {
    t.append(s, a);
  }), t.append("file", e.fileBlob);
  const o = await fetch(r.url, {
    method: "POST",
    body: t
  });
  return o.ok ? {} : (console.error("Failed to upload image", {
    response: await o.text()
  }), { error: "Failed to upload image" });
}, U = () => {
  const { createImageUploadLink: e, completeImageUpload: r } = c();
  return {
    uploadImage: m(
      async (o) => {
        const s = await d(o), a = await e({
          input: [
            {
              mimeType: s.mimeType,
              fileSize: s.fileSize
            }
          ]
        });
        if (!a.ok)
          throw new Error(a.error.message);
        const { error: n } = await f(
          s,
          a?.data?.targets?.[0]
        );
        if (n)
          throw new Error(n);
        let p = 0;
        for (; p < 30; ) {
          const i = await r({
            resourceUrls: a?.data?.targets?.map((l) => l.resourceUrl) || []
          });
          if (!i.ok)
            throw new Error(i.error.message);
          if (i.data?.files?.[0]?.fileStatus === "READY")
            return [
              {
                id: i.data.files[0].id,
                imageUrl: i.data.files[0].image?.url,
                resourceUrl: a?.data?.targets?.[0]?.resourceUrl
              }
            ];
          await new Promise((l) => setTimeout(l, 1e3)), p++;
        }
        throw new Error("Image upload completion timed out");
      },
      [e, r]
    )
  };
};
export {
  U as useImageUpload
};
//# sourceMappingURL=useImageUpload.js.map
