/**
* useIntegrationKey Hook
*
* TanStack Query hook for fetching a single integration key by ID.
*
* Features:
* - Automatic caching with 5-minute stale time
* - Background refetching
* - Request deduplication
* - Loading and error states
*
* @layer Presentation - TanStack Query Hook
*/
import { useQuery } from '@tanstack/react-query';
import { queryKeys } from '@/lib/query-keys';
import { integrationKeysApi } from '@/infrastructure/http/api/integration-keys/api';
import type { IntegrationKey } from '@/domain/entities/IntegrationKey';
interface UseIntegrationKeyOptions {
enabled?: boolean;
}
/**
* Fetches a single integration key by ID
*
* @param id - Integration key ID
* @param options - Query options (enabled, etc.)
* @returns TanStack Query result with integration key data
*
* @example
* ```typescript
* const { data: key, isLoading, error } = useIntegrationKey('key-123');
*
* if (isLoading) return ;
* if (error) return ;
* if (!key) return null;
*
* return ;
* ```
*/
export function useIntegrationKey(id: string | undefined, options?: UseIntegrationKeyOptions) {
return useQuery({
queryKey: queryKeys.integrationKeys.detail(id || ''),
queryFn: async () => {
if (!id) return null;
// Get all keys and find the one we need
// Note: API doesn't have a single key endpoint, so we filter from list
const tenantId = localStorage.getItem('selectedTenantId');
if (!tenantId) {
throw new Error('No tenant selected');
}
const { keys } = await integrationKeysApi.listKeys(tenantId);
const key = keys.find((k) => k.id === id);
return key || null;
},
enabled: options?.enabled !== false && !!id,
staleTime: 5 * 60 * 1000, // 5 minutes
});
}