import { creativeApi } from "@/api/creative";

function saveUrl(url: string, filename: string) {
  const link = document.createElement("a");
  link.href = url;
  link.download = filename;
  document.body.appendChild(link);
  link.click();
  link.remove();
}

export async function downloadFile(url: string, filename: string) {
  saveUrl(url, filename);
}

// downloadBlob 将 Blob 数据以指定文件名保存到本地。
export async function downloadBlob(blob: Blob, filename: string) {
  const objectUrl = URL.createObjectURL(blob);
  try {
    saveUrl(objectUrl, filename);
  } finally {
    window.setTimeout(() => URL.revokeObjectURL(objectUrl), 1000);
  }
}

export async function downloadMedia(mediaId: string | undefined, fallbackUrl: string, filename: string) {
  if (!mediaId) return downloadFile(fallbackUrl, filename);
  const blob = await creativeApi.media(mediaId);
  const objectUrl = URL.createObjectURL(blob);
  try {
    saveUrl(objectUrl, filename);
  } finally {
    window.setTimeout(() => URL.revokeObjectURL(objectUrl), 1000);
  }
}
