import { http } from "./api";

export async function downloadFile(url: string, filename: string) {
  const { data } = await http.get(url, { responseType: "blob" });
  saveBlob(data, filename);
}

export function saveBlob(data: Blob, filename: string) {
  const link = document.createElement("a");
  link.href = URL.createObjectURL(data);
  link.download = filename;
  link.click();
  URL.revokeObjectURL(link.href);
}

export async function apiErrorMessage(error: any, fallback: string) {
  const data = error?.response?.data;
  if (data instanceof Blob) {
    const text = await data.text();
    try {
      return JSON.parse(text).detail || fallback;
    } catch {
      return text || fallback;
    }
  }
  return data?.detail || fallback;
}
