import { useCallback } from 'react';
import { SearchResponse, DocType } from '../types';
import { useApi, buildUrl } from './useApi';
const PAGE_SIZE = 20;
export function useSearch() {
const { data, loading, error, fetchData, reset } = useApi<SearchResponse>();
const search = useCallback(async (
query: string,
type: DocType = 'all',
offset: number = 0
) => {
if (!query.trim()) {
reset();
return null;
}
const url = buildUrl('/search', {
q: query,
type,
limit: PAGE_SIZE,
offset,
});
return fetchData(url);
}, [fetchData, reset]);
const totalPages = data ? Math.ceil(data.total / PAGE_SIZE) : 0;
const currentPage = data ? Math.floor(data.offset / PAGE_SIZE) + 1 : 0;
const hasPrev = data ? data.offset > 0 : false;
const hasNext = data ? data.offset + PAGE_SIZE < data.total : false;
return {
results: data?.results ?? [],
total: data?.total ?? 0,
offset: data?.offset ?? 0,
loading,
error,
search,
reset,
pagination: {
totalPages,
currentPage,
hasPrev,
hasNext,
pageSize: PAGE_SIZE,
},
};
}