import { useQuery, useMutation, useQueryClient } from "@tanstack/react-query";
import {
  BrandingResponse,
  BrandingParam,
  BrandingResponseAPI,
  BrandingParamAPI,
  BrandingResponseItems,
} from "../types/brandTypes";
import {
  getBrandingItems,
  updateBrandingItem,
  createBrandingItem,
  getBrandingItemsUsingDomain,
} from "../services/brandService";
import { useMemo } from "react";
type UpdateBrandingVariables = {
  id: string;
  payload: BrandingParamAPI[];
};
export const useBranding = (
  siteId: string,
  options?: { skipAuthQuery?: boolean },
) => {
  const queryClient = useQueryClient();

  const { data, isLoading, error, refetch } = useQuery<BrandingResponseAPI>({
    queryKey: ["Branding", siteId],
    queryFn: async () => {
      const data = (await getBrandingItems(siteId)).count;
      const resp = await getBrandingItems(siteId, data ? data : 0);
      return resp;
    },
    enabled: !(siteId === "") && !options?.skipAuthQuery,
  });

  const updateMutation = useMutation<
    BrandingResponse,
    Error,
    UpdateBrandingVariables
  >({
    mutationFn: async ({ id, payload }) => {
      const resp = await updateBrandingItem(id, payload);
      return resp;
    },
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ["Branding", siteId] });
      queryClient.invalidateQueries({ queryKey: ["BrandingDomain"] });
    },
  });

  const createMutation = useMutation({
    mutationFn: async (payload: BrandingParamAPI[]) => {
      const resp = await createBrandingItem(payload);
      return resp;
    },
    onSuccess: () => {
      queryClient.invalidateQueries({ queryKey: ["Branding", siteId] });
    },
  });

  return {
    data,
    isLoading,
    error,
    updateItem: updateMutation.mutateAsync,
    isUpdating: updateMutation.isPending,
    createItem: createMutation.mutateAsync,
    isCreating: createMutation.isPending,
    refetch,
  };
};
