import { useMutation, useQueryClient } from '@tanstack/react-query' import { toast } from 'sonner' import { platformWebhooksKeys } from './keys' import { isWebhookRateLimitError, sendTestWebhookEvent, type WebhookScopeParams, } from './platform-webhooks-fetchers' import type { StudioError } from '@/lib/errors/studio-errors' import type { UseCustomMutationOptions } from '@/types' export type WebhookEndpointTestVariables = { scope: WebhookScopeParams id: string eventType?: string } async function testEndpoint({ scope, id, eventType }: WebhookEndpointTestVariables) { return sendTestWebhookEvent(scope, id, eventType) } type WebhookEndpointTestData = Awaited> export const useWebhookEndpointTestMutation = ({ onSuccess, onError, ...options }: Omit< UseCustomMutationOptions, 'mutationFn' > = {}) => { const queryClient = useQueryClient() return useMutation({ mutationFn: testEndpoint, async onSuccess(data, variables, context) { // The test delivery lands asynchronously — invalidate so it shows up once it does. await queryClient.invalidateQueries({ queryKey: platformWebhooksKeys.deliveriesAll(variables.scope, variables.id), }) await onSuccess?.(data, variables, context) }, async onError(data, variables, context) { if (onError === undefined) { if (isWebhookRateLimitError(data)) { toast.error('Too many requests. Wait a minute and try again (limit: 10 per minute).') } else { toast.error(`Failed to send test event: ${data.message}`) } } else { onError(data, variables, context) } }, ...options, }) }