import { useMutation, useQueryClient } from '@tanstack/react-query' import { toast } from 'sonner' import { replicationKeys } from './keys' import { handleError, post } from '@/data/fetchers' import type { ResponseError, UseCustomMutationOptions } from '@/types' export type CreateTenantSourceParams = { projectRef: string } async function createTenantSource({ projectRef }: CreateTenantSourceParams, signal?: AbortSignal) { if (!projectRef) throw new Error('projectRef is required') const { data, error } = await post('/platform/replication/{ref}/tenants-sources', { params: { path: { ref: projectRef } }, signal, }) if (error) { handleError(error) } return data } type CreateTenantSourceData = Awaited> export const useCreateTenantSourceMutation = ({ onSuccess, onError, ...options }: Omit< UseCustomMutationOptions, 'mutationFn' > = {}) => { const queryClient = useQueryClient() return useMutation({ mutationFn: (vars) => createTenantSource(vars), async onSuccess(data, variables, context) { const { projectRef } = variables await queryClient.invalidateQueries({ queryKey: replicationKeys.sources(projectRef) }) await onSuccess?.(data, variables, context) }, async onError(data, variables, context) { if (onError === undefined) { toast.error(`Failed to create tenant or source: ${data.message}`) } else { onError(data, variables, context) } }, ...options, }) }