import { useQuery, useQueryClient } from "@tanstack/react-query";
import { DealProductSchema } from "@/lib/client";
import {
    getDealProductsOptions,
    getDealProductsQueryKey,
} from "@/lib/client/@tanstack/react-query.gen";

type Props = {
    dealId: number;
};

export type DealProductsList = {
    dealProducts: DealProductSchema[];
    setDealProducts: (dealProducts: DealProductSchema[]) => void;
    refetch: () => void;
    queryKey: any[];
};

const useDealProductsList = ({ dealId }: Props): DealProductsList => {
    const queryClient = useQueryClient();
    const options = {
        path: { dealId },
    };
    const { data, refetch } = useQuery({
        ...getDealProductsOptions(options),
        enabled: !!dealId,
    });

    const queryKey = getDealProductsQueryKey(options);

    const setDealProducts = (dealProducts: DealProductSchema[]) => {
        queryClient.setQueryData(
            queryKey,
            (old: { items: DealProductSchema[] }) => ({
                ...old,
                items: dealProducts,
            })
        );
    };

    return {
        dealProducts: data?.items ?? [],
        setDealProducts,
        refetch,
        queryKey,
    };
};

export default useDealProductsList;
