import { useCrudOperations } from "@/hooks/cruds/baseCrud";
import {
    CreateProductSchema,
    ProductSchema,
    UpdateProductSchema,
} from "@/lib/client";
import {
    createProductMutation,
    deleteProductMutation,
    updateProductMutation,
} from "@/lib/client/@tanstack/react-query.gen";

type UseProductsProps = {
    queryKey: any[];
};

export type ProductsCrud = {
    onCreate: (product: CreateProductSchema) => void;
    onUpdate: (
        productId: number,
        product: UpdateProductSchema,
        onSuccess?: () => void
    ) => void;
    onDelete: (product: ProductSchema) => void;
};

export const useProductsCrud = ({
    queryKey,
}: UseProductsProps): ProductsCrud => {
    return useCrudOperations<
        ProductSchema,
        UpdateProductSchema,
        CreateProductSchema
    >({
        key: "getProducts",
        queryKey,
        mutations: {
            create: createProductMutation(),
            update: updateProductMutation(),
            delete: deleteProductMutation(),
        },
        getUpdateEntity: (old, update) =>
            ({
                ...old,
                ...update,
            }) as ProductSchema,
        getDeleteConfirmTitle: () => "Удаление товара",
    });
};
