import { api as client } from "../auth/http";
import { URL_CONSTANTS } from "@/constants/URLS";

const F = URL_CONSTANTS.FILES;

export const filesService = {
  /** Stream a stored file by id (backend route: GET /files/:id). */
  download: async (id: string): Promise<Blob> => {
    const response = await client.get(F.BY_ID(id), { responseType: "blob" });
    return response.data as Blob;
  },
};

/** Download a file blob and trigger a browser save with the given name. */
export async function downloadBookingFile(
  id: string,
  filename: string,
): Promise<void> {
  const blob = await filesService.download(id);
  const url = URL.createObjectURL(blob);
  const a = document.createElement("a");
  a.href = url;
  a.download = filename;
  a.click();
  URL.revokeObjectURL(url);
}
