import { useMutation, useQuery } from "@tanstack/react-query";
import { toast } from "sonner";
import { CAM_BASE } from "../utils/config";

const base_url = `${CAM_BASE}/api`;

const fetchCameraSideConfig = async ({ queryKey }: { queryKey: string[] }) => {
  const [, cameraSide] = queryKey;
  const fetchUrl = `${base_url}/fetch-config?id=${cameraSide}`;
  const response = await fetch(fetchUrl, {
    signal: AbortSignal.timeout(300000),
  });
  if (!response.ok) throw new Error("cannot react cameraSide ");
  return response.json();
};

const updateCamerasideConfig = async (data: { id: string | number; friendlyName: string; cameraAddress: string }) => {
  const updateUrl = `${base_url}/update-config?id=${data.id}`;

  const updateConfigPayload = {
    id: data.friendlyName,
    fields: [
      {
        property: "propURI",
        value: data.cameraAddress,
      },
    ],
  };

  const response = await fetch(updateUrl, {
    method: "POST",
    body: JSON.stringify(updateConfigPayload),
  });
  if (!response.ok) throw new Error("Please make sure fields are filled in correctly");
};

export const useFetchCameraConfig = (cameraSide: string) => {
  const fetchedConfigQuery = useQuery({
    queryKey: ["cameraSideConfig", cameraSide],
    queryFn: fetchCameraSideConfig,
  });

  const updateConfigMutation = useMutation({
    mutationKey: ["cameraSideConfigUpdate"],
    mutationFn: updateCamerasideConfig,
    onError: (error) => toast.error(error.message),
    onSuccess: () => toast("Settings Successfully saved"),
  });

  return {
    data: fetchedConfigQuery.data,
    isPending: fetchedConfigQuery.isPending,
    isError: fetchedConfigQuery.isError,
    updateCameraConfig: updateConfigMutation.mutate,
    updateCameraConfigError: updateConfigMutation.error,
    updateCameraConfigLoading: updateConfigMutation.isPending,
  };
};
