import { useQuery } from "@tanstack/react-query";
import * as api from "../service/MenuService";
import { useParams } from "next/navigation";
import { useEffect } from "react";
import {
  getPersistedCategoriesData,
  getPersistedMenuData,
  setPersistedCategoriesData,
  setPersistedMenuData,
} from "@/lib/helpers/themeCache";

export const useGetProducts = () => {
  const { name } = useParams<{ name: string }>();
  const query = useQuery({
    queryKey: ["menu", name],
    queryFn: async () => {
      const data = await api.getProducts(name);
      setPersistedMenuData(name, data);
      return data;
    },
    enabled: !!name,
    placeholderData: () => (name ? getPersistedMenuData(name) : undefined),
  });

  useEffect(() => {
    if (name && query.data) {
      setPersistedMenuData(name, query.data);
    }
  }, [name, query.data]);

  return query;
};

export const useGetCategories = () => {
  const { name } = useParams<{ name: string }>();
  const query = useQuery({
    queryKey: ["categories", name],
    queryFn: async () => {
      const data = await api.getCategories(name);
      setPersistedCategoriesData(name, data);
      return data;
    },
    enabled: !!name,
    placeholderData: () => (name ? getPersistedCategoriesData(name) : undefined),
  });

  useEffect(() => {
    if (name && query.data) {
      setPersistedCategoriesData(name, query.data);
    }
  }, [name, query.data]);

  return query;
};

export const useGetNotificationsCount = () => {
  return useQuery({
    queryKey: ["notifications-count"],
    queryFn: api.getNotificationsCount,
  });
};
