import { useMutation, useQuery } from "@tanstack/react-query";
import { CAM_BASE } from "../utils/config";
import { toast } from "sonner";
import { getOrCacheBlob } from "../utils/cacheSound";
const camBase = import.meta.env.MODE !== "development" ? CAM_BASE : CAM_BASE;

type UseFileUploadProps = {
  queryKey?: string[];
};

const uploadFile = async (file: File) => {
  const form = new FormData();
  form.append("upload", file, file.name);
  const response = await fetch(`${camBase}/upload/file-upload/3`, {
    method: "POST",
    body: form,
  });
  if (!response.ok) {
    throw new Error("Cannot reach upload file endpoint");
  }
  return response.text();
};

const getUploadFiles = async ({ queryKey }: { queryKey: string[] }) => {
  const [, fileName] = queryKey;
  const url = fileName;
  return getOrCacheBlob(url);
};

export const useFileUpload = ({ queryKey }: UseFileUploadProps) => {
  const query = useQuery({
    queryKey: ["getUploadFiles", ...(queryKey ?? [])],
    queryFn: () => getUploadFiles({ queryKey: ["getUploadFiles", ...(queryKey ?? [])] }),
    enabled: !!queryKey,
  });

  const mutation = useMutation({
    mutationFn: (file: File) => uploadFile(file),
    mutationKey: ["uploadFile"],
    onError: (err) => toast.error(err ? err.message : ""),
    onSuccess: async (msg) => toast.success(msg),
  });

  return { query: queryKey ? query : undefined, mutation };
};
