import { useQuery } from '@tanstack/react-query';
import { fetchPieces, fetchPiece } from '../api';
import { STALE_TIME } from '../lib/constants.js';

export function usePieceList(spaceId?: string) {
  return useQuery({
    queryKey: ['pieces', spaceId ?? null],
    queryFn: () => fetchPieces(spaceId),
    staleTime: STALE_TIME.SEMI_STATIC,
  });
}

/**
 * Fetches a single piece by name (and optional source).
 * Returns the full PieceFetchResult so callers can use the server-resolved source
 * for authorization decisions (e.g. read-only gate in PieceEditor).
 * When `spaceId` is set, resolves against the space folder's custom pieces.
 */
export function usePiece(name: string | undefined, source?: 'builtin' | 'user-custom' | 'global-custom', spaceId?: string) {
  return useQuery({
    queryKey: ['piece', spaceId ?? null, name, source],
    queryFn: () => fetchPiece(name!, source, spaceId),
    enabled: !!name,
    staleTime: STALE_TIME.SEMI_STATIC,
  });
}
