import { useQuery } from "@tanstack/react-query";
import { useParams } from "next/navigation";
import { useEffect } from "react";
import * as api from "../service/AboutService";
import {
  getPersistedAboutData,
  setPersistedAboutData,
} from "@/lib/helpers/themeCache";

export const useGetAbout = () => {
  const { name } = useParams<{ name: string }>();
  const query = useQuery({
    queryKey: ["about", name],
    queryFn: async () => {
      const data = await api.getAbout(name);
      setPersistedAboutData(name, data);
      return data;
    },
    enabled: !!name,
    retry: false,
    staleTime: 60 * 60_000,
    gcTime: 24 * 60 * 60_000,
    refetchOnMount: "always",
    refetchOnWindowFocus: false,
    placeholderData: () => (name ? getPersistedAboutData(name) : undefined),
  });

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

  return query;
};

export const useGetReviews = () => {
  const { name } = useParams<{ name: string }>();
  return useQuery({
    queryKey: ["reviews", name],
    queryFn: () => api.getReviews(name),
    enabled: !!name,
    retry: false,
  });
};

export const useGetSchedules = () => {
  const { name } = useParams<{ name: string }>();
  return useQuery({
    queryKey: ["schedules", name],
    queryFn: () => api.getSchedules(name),
    enabled: !!name,
    retry: false,
  });
};
