import { useMutation, useQuery } from "@tanstack/react-query";
import { sendBlobFileUpload } from "../components/SettingForms/System/Upload";
import { toast } from "sonner";
import { handleSystemSave, handleSystemRecall } from "../components/SettingForms/System/SettingSaveRecall";
import { useEffect } from "react";
import { CAM_BASE } from "../utils/config";
import type { DNSSettingsType } from "../types/types";

const camBase = import.meta.env.MODE !== "development" ? CAM_BASE : "";

const getDNSSettings = async () => {
  const response = await fetch(`${camBase}/api/fetch-config?id=GLOBAL--NetworkConfig`);
  if (!response.ok) throw new Error("Cannot get DNS Settings");
  return response.json();
};

const updateDNSSettings = async (data: DNSSettingsType) => {
  const dnsSettingsPayload = {
    id: "GLOBAL--NetworkConfig",
    fields: [
      {
        property: "propNameServerPrimary",
        value: data?.serverPrimary,
      },
      {
        property: "propNameServerSecondary",
        value: data?.serverSecondary,
      },
    ],
  };
  const response = await fetch(`${camBase}/api/update-config`, {
    method: "post",
    body: JSON.stringify(dnsSettingsPayload),
  });
  if (!response.ok) throw new Error("cannot send to DNS endpoint");

  return response.json();
};

export const useSystemConfig = () => {
  const uploadSettingsMutation = useMutation({
    mutationKey: ["uploadSettings"],
    mutationFn: sendBlobFileUpload,
    onError: (error) =>
      toast.error(error.message, {
        id: "uploadSettings",
      }),
    onSuccess: (test) =>
      toast(test, {
        id: "uploadSettings",
      }),
  });

  const saveSystemSettings = useMutation({
    mutationKey: ["systemSaveSettings"],
    mutationFn: handleSystemSave,
    onError: (error) =>
      toast.error(error.message, {
        id: "systemSettings",
      }),
  });

  const getSystemSettings = useQuery({
    queryKey: ["getSystemSettings"],
    queryFn: handleSystemRecall,
  });

  useEffect(() => {
    if (getSystemSettings.isError)
      toast.error(getSystemSettings.error.message, {
        id: "systemSettings",
      });
  }, [getSystemSettings?.error?.message, getSystemSettings.isError]);

  return {
    uploadSettings: uploadSettingsMutation.mutate,
    saveSystemSettings: saveSystemSettings.mutate,
    systemSettingsData: getSystemSettings.data,
    systemSettingsError: getSystemSettings.error,
    saveSystemSettingsError: saveSystemSettings.isError,
    saveSystemSettingsLoading: saveSystemSettings.isPending,
  };
};

export const useDNSSettings = () => {
  const dnsQuery = useQuery({
    queryKey: ["getDNSSettings"],
    queryFn: getDNSSettings,
  });

  const dnsMutation = useMutation({
    mutationKey: ["updateDNSSettings"],
    mutationFn: updateDNSSettings,
  });

  return {
    dnsQuery,
    dnsMutation,
  };
};
