import useAxios from "axios-hooks";

const useMedia = () => {
  //GET List Media
  const [{ ...getMediaFilesData }, getMediaFiles] = useAxios(
    {
      method: "GET",
    },
    {
      manual: true,
    }
  );
  const handleGetMediaFiles = async () => {
    try {
      await getMediaFiles({
        url: `/media/v1/streams/files`,
      });
    } catch (err) {
      console.log(err);
    }
  };

  //GET Single Media
  const [{ ...getSingleMediaData }, getSingleMedia] = useAxios(
    {
      method: "GET",
    },
    {
      manual: true,
    }
  );
  const handleGetSingleMedia = async (id) => {
    try {
      await getSingleMedia({
        url: `/media/v1/streams/files/${id}`,
      });
    } catch (err) {
      console.log(err);
    }
  };

  //POST Create Media
  const [{ ...uploadMediaData }, uploadMedia] = useAxios(
    {
      method: "POST",
      // url: `/media/v1/enterprise/files/`,
    },
    {
      manual: true,
    }
  );

  const handleUploadMedia = async (
    files,
    account_type,
    enterprise_account_id
  ) => {
    try {
      if (files) {
        console.log(files);
        // console.log("files", files);

        // const formdata = new FormData();
        // formdata.append("upload", files.upload);
        // return await uploadMedia({ data: formdata });
        let apiUrl;

        if (account_type === "instructor") {
          // For instructor account type
          apiUrl = enterprise_account_id
            ? `/media/v1/instructor/${enterprise_account_id}/files/` // Affiliate instructor
            : `/media/v1/${account_type}/files/`; // Non-affiliate instructor
        } else if (account_type === "enterprise") {
          // For enterprise account type
          apiUrl = `/media/v1/${account_type}/files/`; // Enterprise
        } else if (account_type === "personal") {
          // For personal account type
          apiUrl = `/media/v1/files/`;
        } else {
          // throw new Error("Invalid account type"); // Optional error handling for unexpected types
          console.log("Invalid account type");
        }

        return await uploadMedia({ url: apiUrl, data: files });
      } else {
        return false;
      }
    } catch (err) {
      console.log(err);
    }
  };
  return {
    getMediaFilesData,
    handleGetMediaFiles,
    getSingleMediaData,
    handleGetSingleMedia,
    uploadMediaData,
    handleUploadMedia,
  };
};

export default useMedia;
