import { useMutation, useQuery, useQueryClient, type QueryClient } from '@tanstack/react-query'; import { createManagedContentCatalog, deleteManagedContentCatalog, getContentCatalog, getManagedContentCatalog, updateManagedContentCatalog, } from '@/shared/api/contentCatalog'; import { CONTENT_CATALOG_QUERY_KEYS } from '@/shared/constants/contentCatalog'; export function useContentCatalogPayload( contentType: string, emptyPayload: TPayload, options?: { readonly enabled?: boolean }, ) { const query = useQuery({ queryKey: [...CONTENT_CATALOG_QUERY_KEYS.content, contentType], queryFn: async () => { const response = await getContentCatalog(contentType); return response.payload; }, enabled: options?.enabled ?? true, }); return { payload: query.data ?? emptyPayload, isLoading: query.isLoading, error: query.error, refresh: query.refetch, }; } export function useManagedContentCatalog( contentType: string, options?: { readonly enabled?: boolean }, ) { return useQuery({ queryKey: [...CONTENT_CATALOG_QUERY_KEYS.content, 'managed', contentType], queryFn: () => getManagedContentCatalog(contentType), enabled: options?.enabled ?? true, }); } export function useSaveManagedContentCatalog( contentType: string, hasExistingContent: boolean, getPayload: () => TPayload, ) { const queryClient = useQueryClient(); return useMutation({ mutationFn: () => ( hasExistingContent ? updateManagedContentCatalog(contentType, { payload: getPayload() }) : createManagedContentCatalog({ content_type: contentType, payload: getPayload(), }) ), onSuccess: async () => { await invalidateContentCatalogQueries(queryClient, contentType); }, }); } export function useDeleteManagedContentCatalog(contentType: string) { const queryClient = useQueryClient(); return useMutation({ mutationFn: () => deleteManagedContentCatalog(contentType), onSuccess: async () => { await invalidateContentCatalogQueries(queryClient, contentType); }, }); } async function invalidateContentCatalogQueries( queryClient: QueryClient, contentType: string, ): Promise { await Promise.all([ queryClient.invalidateQueries({ queryKey: [...CONTENT_CATALOG_QUERY_KEYS.content, contentType] }), queryClient.invalidateQueries({ queryKey: [...CONTENT_CATALOG_QUERY_KEYS.content, 'managed', contentType] }), ]); }