"use client";
import { useFileInfo } from "@/hooks/queries";
import { fileService } from "@/lib/api";
import { saveBlobFromAxiosResponse } from "@/utils/shared";
import { useState } from "react";

/**
 * Loads metadata for a single document file id and exposes a download action.
 * Keeps the `DocumentItem` view free of data-fetching / side effects.
 */
const useDocumentItemPresenter = (fileId: string) => {
  const { data: info, isLoading } = useFileInfo(fileId);
  const [isDownloading, setIsDownloading] = useState(false);

  const download = async () => {
    setIsDownloading(true);
    try {
      const response = await fileService.downloadFile(fileId);
      saveBlobFromAxiosResponse(response, info?.filename ?? fileId);
    } catch (error) {
      console.error("ERROR caught while downloading document:", error);
    } finally {
      setIsDownloading(false);
    }
  };

  return { info, isLoading, isDownloading, download };
};

export default useDocumentItemPresenter;
