import { useMutation } from "@tanstack/react-query";
import { AxiosError } from "axios";
import {
    CreateProductServiceSchema,
    ProductServiceSchema,
    HttpValidationError,
    UpdateProductServiceSchema,
} from "@/lib/client";
import {
    createDealProductServiceMutation,
    deleteDealProductServiceMutation,
    updateDealProductServiceMutation,
} from "@/lib/client/@tanstack/react-query.gen";
import { notifications } from "@/lib/notifications";

export type DealProductServicesCrud = {
    onCreate: (data: CreateProductServiceSchema) => void;
    onUpdate: (
        dealId: number,
        productId: number,
        serviceId: number,
        data: UpdateProductServiceSchema
    ) => void;
    onDelete: (data: ProductServiceSchema) => void;
};

type Props = {
    refetchDealProducts: () => void;
};

const useProductServiceCrud = ({
    refetchDealProducts,
}: Props): DealProductServicesCrud => {
    const onError = (error: AxiosError<HttpValidationError>, _: any) => {
        console.error(error);
        notifications.error({
            message: error.response?.data?.detail as string | undefined,
        });
    };

    const createMutation = useMutation({
        ...createDealProductServiceMutation(),
        onError,
    });

    const updateMutation = useMutation({
        ...updateDealProductServiceMutation(),
        onError,
    });

    const deleteMutation = useMutation({
        ...deleteDealProductServiceMutation(),
        onError,
    });

    const onCreate = (entity: CreateProductServiceSchema) => {
        createMutation.mutate(
            {
                body: {
                    entity,
                },
            },
            { onSuccess: refetchDealProducts }
        );
    };

    const onUpdate = (
        dealId: number,
        productId: number,
        serviceId: number,
        entity: UpdateProductServiceSchema
    ) => {
        updateMutation.mutate(
            {
                body: {
                    entity,
                },
                path: {
                    dealId,
                    productId,
                    serviceId,
                },
            },
            { onSuccess: refetchDealProducts }
        );
    };

    const onDelete = (entity: ProductServiceSchema) => {
        deleteMutation.mutate(
            { path: entity },
            { onSuccess: refetchDealProducts }
        );
    };

    return {
        onCreate,
        onUpdate,
        onDelete,
    };
};

export default useProductServiceCrud;
