import type { AccessRuleView, CreateGrantInput } from '@dorfteich/shared'; import { useQuery, useQueryClient, type UseQueryResult } from '@tanstack/react-query'; import { apiDelete, apiGet, apiPost } from '../lib/api'; /** Query key for a pond's enriched access rules (issue #55). */ export const accessRulesKey = (pondId: string): string[] => ['access-rules', pondId]; /** The pond's grants enriched with subject/scope names (Pond-Admin only). */ export function useAccessRules(pondId: string | undefined): UseQueryResult { return useQuery({ queryKey: accessRulesKey(pondId ?? ''), queryFn: () => apiGet(`/ponds/${pondId}/grants/access-rules`), enabled: Boolean(pondId), retry: false, // a non-admin gets 403 — do not hammer the endpoint }); } /** Add/remove access-rule grants; each refreshes the rule list. */ export function useAccessRuleMutations(pondId: string): { add: (input: CreateGrantInput) => Promise; remove: (grantId: string) => Promise; } { const queryClient = useQueryClient(); const invalidate = (): Promise => queryClient.invalidateQueries({ queryKey: accessRulesKey(pondId) }); return { add: async (input) => { await apiPost(`/ponds/${pondId}/grants`, input); await invalidate(); }, remove: async (grantId) => { await apiDelete(`/ponds/${pondId}/grants/${grantId}`); await invalidate(); }, }; }