import { useQuery, useQueryClient } from "@tanstack/react-query";
import { DealServiceSchema } from "@/lib/client";
import {
    getDealServicesOptions,
    getDealServicesQueryKey,
} from "@/lib/client/@tanstack/react-query.gen";

type Props = {
    dealId: number;
};

export type DealServicesList = {
    dealServices: DealServiceSchema[];
    setDealServices: (dealServices: DealServiceSchema[]) => void;
    refetch: () => void;
    queryKey: any[];
};

const useDealServicesList = ({ dealId }: Props): DealServicesList => {
    const queryClient = useQueryClient();
    const options = {
        path: { dealId },
    };
    const { data, refetch } = useQuery({
        ...getDealServicesOptions(options),
        enabled: !!dealId,
    });

    const queryKey = getDealServicesQueryKey(options);

    const setDealServices = (dealServices: DealServiceSchema[]) => {
        queryClient.setQueryData(
            queryKey,
            (old: { items: DealServiceSchema[] }) => ({
                ...old,
                items: dealServices,
            })
        );
    };

    return {
        dealServices: data?.items ?? [],
        setDealServices,
        refetch,
        queryKey,
    };
};

export default useDealServicesList;
