/** * Webhooks API client and React Query hooks. */ import { apiGet, apiPost, apiPatch, apiDelete } from '@/api/client'; import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query'; export interface Webhook { id: string; tenant_id: string; url: string; events: string[]; secret: string | null; is_active: boolean; retry_count: number; timeout_seconds: number; created_by: string | null; updated_by: string | null; created_at: string; updated_at: string; } export interface CreateWebhookPayload { url: string; events: string[]; secret?: string | null; is_active?: boolean; retry_count?: number; timeout_seconds?: number; } export interface UpdateWebhookPayload { url?: string; events?: string[]; secret?: string | null; is_active?: boolean; retry_count?: number; timeout_seconds?: number; } export interface WebhookTestResult { success: boolean; status_code: number | null; error: string | null; } // ─── API Functions ────────────────────────────────────────────────────────── export async function fetchWebhooks(event?: string): Promise { const params = event ? `?event=${encodeURIComponent(event)}` : ''; return apiGet(`/webhooks${params}`); } export async function fetchWebhook(id: string): Promise { return apiGet(`/webhooks/${id}`); } export async function createWebhook(data: CreateWebhookPayload): Promise { return apiPost('/webhooks', data); } export async function updateWebhook(id: string, data: UpdateWebhookPayload): Promise { return apiPatch(`/webhooks/${id}`, data); } export async function deleteWebhook(id: string): Promise { return apiDelete(`/webhooks/${id}`); } export async function testWebhook(id: string): Promise { return apiPost(`/webhooks/${id}/test`); } // ─── React Query Hooks ─────────────────────────────────────────────────────── export function useWebhooks(event?: string) { return useQuery({ queryKey: ['webhooks', event], queryFn: () => fetchWebhooks(event), }); } export function useWebhook(id: string) { return useQuery({ queryKey: ['webhooks', id], queryFn: () => fetchWebhook(id), enabled: !!id, }); } export function useCreateWebhook() { const queryClient = useQueryClient(); return useMutation({ mutationFn: (data: CreateWebhookPayload) => createWebhook(data), onSuccess: () => { queryClient.invalidateQueries({ queryKey: ['webhooks'] }); }, }); } export function useUpdateWebhook() { const queryClient = useQueryClient(); return useMutation({ mutationFn: ({ id, data }: { id: string; data: UpdateWebhookPayload }) => updateWebhook(id, data), onSuccess: () => { queryClient.invalidateQueries({ queryKey: ['webhooks'] }); }, }); } export function useDeleteWebhook() { const queryClient = useQueryClient(); return useMutation({ mutationFn: (id: string) => deleteWebhook(id), onSuccess: () => { queryClient.invalidateQueries({ queryKey: ['webhooks'] }); }, }); } export function useTestWebhook() { return useMutation({ mutationFn: (id: string) => testWebhook(id), }); }