import { useQuery, useQueryClient } from "@tanstack/react-query";
import { StatusSchema } from "@/lib/client";
import {
    getStatusesOptions,
    getStatusesQueryKey,
} from "@/lib/client/@tanstack/react-query.gen";

type Props = {
    boardId?: number;
};

const useStatusesList = ({ boardId }: Props) => {
    const queryClient = useQueryClient();
    const options = {
        path: { boardId: boardId ?? 0 },
    };
    const { data, refetch } = useQuery({
        ...getStatusesOptions(options),
        enabled: !!boardId,
    });

    const queryKey = getStatusesQueryKey(options);

    const setStatuses = (statuses: StatusSchema[]) => {
        queryClient.setQueryData(
            queryKey,
            (old: { items: StatusSchema[] }) => ({
                ...old,
                items: statuses,
            })
        );
    };

    return {
        statuses: data?.items ?? [],
        setStatuses,
        refetch,
        queryKey,
    };
};

export default useStatusesList;
