import { useState } from "react";

export const useFileLoader = () => {
  const [files, setFiles] = useState<Record<string, File[]>>({});
  const [base64, setBase64] = useState<Record<string, string[]>>({});

  const loadFromAwsPaths = async (paths: string[] | string, key: string) => {
    const toLoad = Array.isArray(paths) ? paths : [paths];

    const fetchedBase64s = await Promise.all(
      toLoad.map(async (url) => {
        const response = await fetch(url);
        const blob = await response.blob();
        const reader = new FileReader();
        return await new Promise<string>((resolve, reject) => {
          reader.onloadend = () => resolve(reader.result as string);
          reader.onerror = reject;
          reader.readAsDataURL(blob);
        });
      })
    );

    setBase64((prev) => ({
      ...prev,
      [key]: fetchedBase64s,
    }));

    return fetchedBase64s;
  };

  return {
    files,
    base64,
    loadFromAwsPaths,
  };
};
