export default function useFile() {
  const baseUrl = useRuntimeConfig().public.API_DO_STORAGE_ENDPOINT;
  const baseUrlAnpr = useRuntimeConfig().public.API_DO_STORAGE_ENDPOINT_ANPR;

  function addFile(file: File | null) {
    if (!file) {
      throw new Error("File not found.");
    }

    const formData = new FormData();
    formData.append("file", file);

    return useNuxtApp().$api<Record<string, any>>("/api/files", {
      method: "POST",
      body: formData,
    });
  }

  function getFileUrl(id: string) {
    return `${baseUrl}/${id}`;
  }

  function getFileUrlAnpr(id: string) {
    return `${baseUrlAnpr}/${id}`;
  }

  async function urlToFile(url: string, filename: string): Promise<File> {
    const response = await fetch(url);
    const blob = await response.blob();

    // Try to extract MIME type if possible (e.g. image/png)
    const mimeType = blob.type || "image/jpeg";

    return new File([blob], filename, { type: mimeType });
  }

  function deleteFile(attachmentId: string) {
    return useNuxtApp().$api<Record<string, any>>(`/api/files/deleted/file`, {
      method: "PUT",
      query: { id: attachmentId },
    });
  }

  function getFileById(id: string) {
    return useNuxtApp().$api<Record<string, any>>(`/api/files/id/${id}`, {
      method: "GET",
    });
  }

  return {
    baseUrl,
    addFile,
    deleteFile,
    urlToFile,
    getFileUrl,
    getFileById,
    getFileUrlAnpr
  };
}
