import { fetchFile } from "@/apis/user";
import { useToast } from "@/hooks/use-toast";
import { useAbortController } from "@/hooks/useAbortController";
import { useContext, useEffect } from "react";
import { useSearchParams } from "react-router-dom";
import { ReportContext } from "../Provider/ReportResolveProvider";
import { RealtimeClientContext } from "../Provider/RealtimeClientProvider";



export default function AntechamberFile() {
  const [searchParams] = useSearchParams();
  const fileId = searchParams.get("fileId") || "";
  const locationCode = searchParams.get("locationCode") || "";
  const token = searchParams.get("token") || "";
  const { toast } = useToast();
  const { getSignal } = useAbortController();
  const { setHasHandledReport,hasHandledReport } = useContext(ReportContext);
  const { handleConnect } = useContext(RealtimeClientContext);

  const useFileFetch = async () => {
    const result = await fetchFile({
      params: { id: fileId, location: locationCode },
      options: {
        signal: getSignal(),
        headers: { Authorization: `Bearer ${token}` },
      },
    });
    if (result.message) {
      toast({
        title: result.message,
      });
    }
    let url = result.result as string;
    
    handleConnect({
      fileUrl: url,
    });
    setHasHandledReport(true);
  };


  useEffect(() => {
    if (fileId && locationCode && !hasHandledReport) {
      useFileFetch();
    }
  }, [fileId, locationCode,hasHandledReport]);


  return <></>;
}
