import { GetServiceKitSchema, ServiceService } from "../../../client";
import { omit } from "lodash";
import { notifications } from "../../../shared/lib/notifications.ts";
import { modals } from "@mantine/modals";
import useServicesKitsList from "./useServicesKitsList.tsx";

const useServicesKitsState = () => {
    const { objects: servicesKits, refetch: refetchKits } =
        useServicesKitsList();

    const onKitCreate = (kit: GetServiceKitSchema) => {
        ServiceService.createServicesKit({
            requestBody: {
                data: {
                    ...omit(kit, ["services", "id"]),
                    servicesIds: kit.services.map(service => service.id),
                },
            },
        }).then(async ({ ok, message }) => {
            notifications.guess(ok, { message: message });
            if (!ok) return;
            await refetchKits();
        });
    };

    const onKitCreateClick = () => {
        modals.openContextModal({
            modal: "serviceKitModalForm",
            title: "Создание набора услуг",
            withCloseButton: false,
            innerProps: {
                onCreate: onKitCreate,
            },
        });
    };
    const onKitUpdate = (kit: GetServiceKitSchema) => {
        ServiceService.updateServicesKit({
            requestBody: {
                data: {
                    ...omit(kit, ["services"]),
                    servicesIds: kit.services.map(service => service.id),
                },
            },
        }).then(async ({ ok, message }) => {
            notifications.guess(ok, { message: message });
            if (!ok) return;
            await refetchKits();
        });
    };

    return {
        onKitCreateClick,
        onKitUpdate,
        servicesKits,
    };
};

export default useServicesKitsState;
