import { useMutation } from "@tanstack/react-query";
import { ModuleSchemaOutput } from "@/lib/client";
import { updateModuleMutation } from "@/lib/client/@tanstack/react-query.gen";

export type ModuleInfo = {
    label: string;
    description: string | null;
};

type Props = {
    module?: ModuleSchemaOutput;
    refetchModule: () => void;
};

export type ModulesActions = {
    updateCommonInfo: (values: ModuleInfo, onSuccess?: () => void) => void;
};

const useModulesActions = ({
    module,
    refetchModule,
}: Props): ModulesActions => {
    const updateCommonInfoMutation = useMutation(updateModuleMutation());

    const updateCommonInfo = (values: ModuleInfo, onSuccess?: () => void) => {
        if (!module) return;

        updateCommonInfoMutation.mutate(
            {
                path: {
                    pk: module.id,
                },
                body: {
                    entity: values,
                },
            },
            {
                onSuccess: () => {
                    refetchModule();
                    onSuccess && onSuccess();
                },
            }
        );
    };

    return {
        updateCommonInfo,
    };
};

export default useModulesActions;
