import { useQuery, useQueryClient } from "@tanstack/react-query";
import { BoardSchema } from "@/lib/client";
import {
    getBoardsOptions,
    getBoardsQueryKey,
} from "@/lib/client/@tanstack/react-query.gen";

type Props = {
    projectId?: number;
};

const useBoardsList = ({ projectId }: Props) => {
    const queryClient = useQueryClient();
    const options = {
        path: { projectId: projectId ?? 0 },
    };
    const { data, refetch } = useQuery({
        ...getBoardsOptions(options),
        enabled: !!projectId,
    });

    const queryKey = getBoardsQueryKey(options);

    const setBoards = (boards: BoardSchema[]) => {
        queryClient.setQueryData(queryKey, (old: { items: BoardSchema[] }) => ({
            ...old,
            items: boards,
        }));
    };

    return {
        boards: data?.items ?? [],
        setBoards,
        refetch,
        queryKey,
    };
};

export default useBoardsList;
