import { API_ENDPOINTS } from "@/lib/api";
import { cmsService } from "@/lib/api/services/cms-service";
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
import { useRouter } from "next/navigation";
import { useMemo } from "react";
import { toast } from "react-toastify";

export const useGetCmsList = (params?: Record<string, any>) => {
  const queryKey = useMemo(() => [API_ENDPOINTS.CMS.BASE(), params], [params]);
  return useQuery({
    queryKey,
    queryFn: () => cmsService.getCms(params),
  });
};
export const useGetCmsDetails = (id: string) => {
  const queryKey = useMemo(() => [API_ENDPOINTS.CMS.BASE(id)], [id]);
  return useQuery({
    queryKey,
    queryFn: () => cmsService.getCmsDetails(id),
  });
};
export const useCreateCms = () => {
  const router = useRouter();
  const queryClient = useQueryClient();
  const mutationKey = useMemo(
    () => [API_ENDPOINTS.CMS.BASE(), "Create cms"],
    [],
  );
  return useMutation({
    mutationKey,
    mutationFn: cmsService.createCms,
    onSuccess: ({ data }: { data: { message: string } }) => {
      toast.success(data.message);
      router.push("/marketing");
      queryClient.invalidateQueries({
        queryKey: [API_ENDPOINTS.CMS.BASE()],
      });
    },
  });
};
export const useDeleteCms = (successCallback?: () => void) => {
  const queryClient = useQueryClient();
  const mutationKey = useMemo(
    () => [API_ENDPOINTS.CMS.BASE(), "Delete CMS"],
    [],
  );
  return useMutation({
    mutationKey,
    mutationFn: cmsService.deleteCms,
    onSuccess: ({ data }: { data: { message: string } }) => {
      toast.success(data.message);
      successCallback?.();
      queryClient.invalidateQueries({
        queryKey: [API_ENDPOINTS.CMS.BASE()],
      });
    },
  });
};
export const useUpdateCms = (id: string) => {
  const router = useRouter();
  const queryClient = useQueryClient();
  const mutationKey = useMemo(
    () => [API_ENDPOINTS.CMS.BASE(id), "Update cms"],
    [id],
  );
  return useMutation({
    mutationKey,
    mutationFn: (data: any) => cmsService.updateCms({ id, data }),
    onSuccess: () => {
      toast.success("CMS updated successfully");
      router.push("/marketing");
      queryClient.invalidateQueries({
        queryKey: [API_ENDPOINTS.CMS.BASE()],
      });
      queryClient.invalidateQueries({
        queryKey: [API_ENDPOINTS.CMS.BASE(id)],
      });
    },
  });
};
