import {QueryObserverResult, RefetchOptions, useQuery} from "@tanstack/react-query";
import {CancelablePromise, PaginationInfoSchema} from "../client";
import {Pagination} from "../types/Pagination.ts";

type Props<T, K> = {
    queryFn: () => CancelablePromise<T>,
    getObjectsFn: (response: T) => K[],
    queryKey: string
}
type Response<T, K> = {
    objects: K[],
    refetch: (options?: RefetchOptions) => Promise<QueryObserverResult<T, Error>>
}
const ObjectList = <T, K, >(props: Props<T, K>): Response<T, K> => {
    const {isPending, error, data, refetch} = useQuery({
        queryKey: [props.queryKey],
        queryFn: props.queryFn
    });
    const objects = isPending || error || !data ? ([] as K[]) : props.getObjectsFn(data);
    return {objects, refetch}
}

interface ObjectWithPagination {
    paginationInfo: PaginationInfoSchema
}

type PropsWithPagination<T extends ObjectWithPagination, K> = {
    queryFn: () => CancelablePromise<T>,
    getObjectsFn: (response: T) => K[],
    queryKey: string,
    pagination: Pagination
}
type ResponseWithPagination<T extends ObjectWithPagination, K> = {
    objects: K[],
    pagination?: PaginationInfoSchema,
    refetch: (options?: RefetchOptions) => Promise<QueryObserverResult<T, Error>>
}
export const ObjectListWithPagination = <T extends ObjectWithPagination, K, >(props: PropsWithPagination<T, K>): ResponseWithPagination<T, K> => {
    const {isPending, error, data, refetch} = useQuery({
        queryKey: [props.queryKey, props, props.pagination.itemsPerPage, props.pagination.page],
        queryFn: props.queryFn,
    });
    const objects = isPending || error || !data ? ([] as K[]) : props.getObjectsFn(data);
    return {
        objects,
        pagination: data?.paginationInfo,
        refetch
    }
}

export default ObjectList