import { useInfiniteQuery, useMutation, useQueryClient, } from '@tanstack/react-query';
import { useMemo } from 'react';
import { apiClient } from '../lib/api-client';
const SESSIONS_PAGE_SIZE = 50;
export const sessionsQueryKey = ['sessions', 'list'];
export function useSessionsInfinite() {
    return useInfiniteQuery({
        queryKey: sessionsQueryKey,
        queryFn: ({ pageParam = 0 }) => apiClient.getSessionsPage({
            limit: SESSIONS_PAGE_SIZE,
            offset: pageParam,
        }),
        getNextPageParam: (lastPage) => lastPage.nextOffset ?? undefined,
        initialPageParam: 0,
        staleTime: 30_000,
        refetchInterval: 30_000,
        refetchOnWindowFocus: false,
    });
}
export function useSessions() {
    const query = useSessionsInfinite();
    const data = useMemo(() => {
        if (!query.data?.pages)
            return [];
        return query.data.pages.flatMap((p) => p.items ?? []);
    }, [query.data]);
    return {
        data,
        isLoading: query.isLoading,
        isError: query.isError,
        error: query.error,
        hasNextPage: query.hasNextPage,
        fetchNextPage: query.fetchNextPage,
        isFetchingNextPage: query.isFetchingNextPage,
    };
}
export function useSession(sessionId) {
    const { data: sessions } = useSessions();
    return sessions?.find((s) => s.id === sessionId);
}
export function useCreateSession() {
    const queryClient = useQueryClient();
    return useMutation({
        mutationFn: (data) => apiClient.createSession(data),
        onSuccess: (newSession) => {
            queryClient.setQueryData(sessionsQueryKey, (old) => {
                if (!old)
                    return old;
                const firstPage = old.pages[0];
                if (!firstPage)
                    return old;
                return {
                    ...old,
                    pages: [
                        { ...firstPage, items: [newSession, ...firstPage.items] },
                        ...old.pages.slice(1),
                    ],
                };
            });
            queryClient.invalidateQueries({ queryKey: sessionsQueryKey });
        },
    });
}
export function useUpdateSession(sessionId) {
    const queryClient = useQueryClient();
    return useMutation({
        mutationFn: (data) => apiClient.updateSession(sessionId, data),
        onSuccess: async () => {
            await queryClient.invalidateQueries({ queryKey: sessionsQueryKey });
            await queryClient.invalidateQueries({ queryKey: ['session', sessionId] });
        },
    });
}
export function useDeleteSession() {
    const queryClient = useQueryClient();
    return useMutation({
        mutationFn: (sessionId) => apiClient.deleteSession(sessionId),
        onSuccess: () => {
            queryClient.invalidateQueries({ queryKey: sessionsQueryKey });
        },
    });
}
//# sourceMappingURL=useSessions.js.map