import { resolveStorageUrl } from "../config/runtime";

export async function downloadFileFromUrl(fileUrl: string, fileName: string) {
  const response = await fetch(resolveStorageUrl(fileUrl), {
    credentials: "include"
  });
  if (!response.ok) {
    throw new Error(`文件下载失败：${response.status} ${response.statusText}`);
  }

  const blob = await response.blob();
  const objectUrl = URL.createObjectURL(blob);
  try {
    const anchor = document.createElement("a");
    anchor.href = objectUrl;
    anchor.download = ensureGlbFileName(fileName);
    anchor.rel = "noopener";
    anchor.style.display = "none";
    document.body.appendChild(anchor);
    anchor.click();
    anchor.remove();
  } finally {
    window.setTimeout(() => URL.revokeObjectURL(objectUrl), 1000);
  }
}

function ensureGlbFileName(fileName: string) {
  const name = fileName.trim() || "model.glb";
  return name.toLowerCase().endsWith(".glb") ? name : `${name}.glb`;
}
