import { useMutation, useQuery } from "@tanstack/react-query";
import { CAM_BASE } from "../utils/config";
import type { InitialValuesForm } from "../types/types";

const getSightingAmend = async () => {
  const response = await fetch(`${CAM_BASE}/api/fetch-config?id=SightingAmmendA`);
  if (!response.ok) throw new Error("Cannot reach sighting amend endpoint");
  return response.json();
};

const updateSightingAmend = async (data: InitialValuesForm) => {
  const updateSightingAmendPayload = {
    id: "SightingAmmendA",
    fields: [
      {
        property: "propOverviewQuality",
        value: data.overviewQuality,
      },
      {
        property: "propOverviewImageScaleFactor",
        value: data.cropSizeFactor,
      },
    ],
  };
  const response = await fetch(`${CAM_BASE}/api/update-config`, {
    method: "Post",
    body: JSON.stringify(updateSightingAmendPayload),
  });
  if (!response.ok) throw new Error("cannot update camera control");
  return response.json();
};

export const useSightingAmend = () => {
  const sightingAmendQuery = useQuery({
    queryKey: ["getSightingAmend"],
    queryFn: getSightingAmend,
  });

  const sightingAmendMutation = useMutation({
    mutationKey: ["updateSightingAmend"],
    mutationFn: updateSightingAmend,
  });

  return {
    sightingAmendQuery,
    sightingAmendMutation,
  };
};
