import type { Storageindex } from "~/schemas/public/Storageindex";
import type { TempTokensToken } from "~/schemas/public/TempTokens";

export const handleDownload = async ({
  file,
  getToken,
}: {
  file: Storageindex;
  getToken: () => Promise<TempTokensToken | TempTokensToken[]>;
}) => {
  const auth_token = (await getToken()) as TempTokensToken;
  try {
    const response = await fetch(
      `/go-api/storage/get/${file.id}${file.ext}?token=${auth_token}`,
    );

    if (!response.ok) {
      throw new Error("File fetch failed");
    }

    const blob = await response.blob();
    const url = window.URL.createObjectURL(blob);
    const a = document.createElement("a");
    a.href = url;
    a.download = file.filename!;
    document.body.appendChild(a);
    a.click();
    a.remove();
    window.URL.revokeObjectURL(url);
  } catch {
    throw new Error("File download failed");
  }
};
