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

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

const getAllBlackboardData = async () => {
  const response = await fetch(`${camBase}/api/blackboard`, {
    signal: AbortSignal.timeout(300000),
  });
  if (!response.ok) {
    throw new Error("Failed to fetch blackboard data");
  }
  return response.json();
};

const viewBlackboardData = async (options: CameraBlackBoardOptions) => {
  const response = await fetch(`${camBase}/api/blackboard`, {
    method: "POST",
    headers: { "Content-Type": "application/json" },
    body: JSON.stringify(options),
  });
  if (!response.ok) {
    throw new Error("Failed to fetch blackboard data");
  }
  return response.json();
};

export const useCameraBlackboard = () => {
  const query = useQuery({
    queryKey: ["cameraBlackboard"],
    queryFn: getAllBlackboardData,
  });

  const mutation = useMutation({
    mutationKey: ["cameraBlackboard"],
    mutationFn: (options?: CameraBlackBoardOptions) =>
      viewBlackboardData({
        operation: options?.operation,
        path: options?.path,
        value: options?.value,
      }),
    onError: (error) => {
      toast.error(`${error.message}`, {
        id: "viewBlackboardData",
      });
    },
  });

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

  return { query, mutation };
};
