import { assetUrl } from "../../../api";

export function attachmentDownloadUrl(postId: string, attachmentId: string) {
  return assetUrl(
    `/api/posts/${encodeURIComponent(postId)}/attachments/${encodeURIComponent(
      attachmentId,
    )}/download`,
  );
}

export async function downloadAttachment(
  postId: string,
  attachmentId: string,
  filename: string,
) {
  return downloadFile(attachmentDownloadUrl(postId, attachmentId), filename);
}

export async function downloadFile(url: string, filename: string) {
  triggerDownload(url, filename || "download");
}

function triggerDownload(url: string, filename: string) {
  const a = document.createElement("a");
  a.href = url;
  a.download = filename;
  a.style.display = "none";
  document.body.append(a);
  a.click();
  a.remove();
}
