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

export function usePieceList() {
  return useQuery({ queryKey: ['pieces'], queryFn: fetchPieces, 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).
 */
export function usePiece(name: string | undefined, source?: 'builtin' | 'user-custom' | 'global-custom') {
  return useQuery({
    queryKey: ['piece', name, source],
    queryFn: () => fetchPiece(name!, source),
    enabled: !!name,
    staleTime: STALE_TIME.SEMI_STATIC,
  });
}
