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

const sendToValidate = async (data: InitialValuesForm) => {
  const updateConfigPayload = {
    id: `Dispatcher-${data.format.toLowerCase()}`,
    fields: [
      {
        property: "propBackofficeURL",
        value: data.backOfficeURL,
      },
      {
        property: "propConnectTimeoutSeconds",
        value: data.connectTimeoutSeconds,
      },
      {
        property: "propPassword",
        value: data.password,
      },
      {
        property: "propReadTimeoutSeconds",
        value: data.readTimeoutSeconds,
      },
      {
        property: "propUsername",
        value: data.username,
      },
    ],
  };
  const response = await fetch(`${CAM_BASE}/api/update-config-isvalid`, {
    method: "post",
    body: JSON.stringify(updateConfigPayload),
  });
  if (!response.ok) throw new Error("Cannot send to validate");
  return response.json();
};

export const useFormVaidate = () => {
  const validateMutation = useMutation({
    mutationKey: ["sendToValidate"],
    mutationFn: sendToValidate,
  });

  return { validateMutation };
};
