import { client } from "@/utils/api";

/**
 * GET /api/files/:id is authenticated (global JwtGuard) — raw browser loads
 * (<img>/<iframe>/<a href>) carry no Bearer token and 401. Always fetch the
 * bytes through the axios client; hand out blob object URLs for previews.
 */
export const filesService = {
  /** Stream a stored file by id (backend route: GET /api/files/:id). */
  download: async (id: string): Promise<Blob> => {
    const response = await client.get(`/api/files/${id}`, {
      responseType: "blob",
    });
    return response.data as Blob;
  },
};

/** Fetch a stored file and return a viewer-ready blob object URL. */
export async function fetchViewableFile(
  id: string,
  name: string,
): Promise<{ name: string; url: string; mimeType?: string }> {
  const blob = await filesService.download(id);
  return {
    name,
    url: URL.createObjectURL(blob),
    mimeType: blob.type || undefined,
  };
}

/** Download a stored file and trigger a browser save with the given name. */
export async function downloadStoredFile(
  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);
}
