import { LexoRank } from "lexorank";
import { useCrudOperations } from "@/hooks/cruds/baseCrud";
import {
    CreateServiceCategorySchema,
    ServiceCategorySchema,
    UpdateServiceCategorySchema,
} from "@/lib/client";
import {
    createServiceCategoryMutation,
    deleteServiceCategoryMutation,
    updateServiceCategoryMutation,
} from "@/lib/client/@tanstack/react-query.gen";
import { ServiceType } from "@/modules/dealModularEditorTabs/FulfillmentBase/shared/types/service";
import { getMaxLexorankByKey } from "@/utils/lexorank/max";
import { getNewLexorank } from "@/utils/lexorank/generation";

type UseServiceCategoryProps = {
    queryKey: any[];
    categories: ServiceCategorySchema[];
};

export type ServiceCategoriesCrud = {
    onCreate: (category: CreateServiceCategorySchema) => void;
    onUpdate: (
        categoryId: number,
        category: UpdateServiceCategorySchema,
        onSuccess?: () => void
    ) => void;
    onDelete: (service: ServiceCategorySchema) => void;
};

export const useServiceCategoriesCrud = ({
    queryKey,
    categories,
}: UseServiceCategoryProps): ServiceCategoriesCrud => {
    const getCategoryRank = (serviceType: ServiceType): string => {
        const lastCategory = getMaxLexorankByKey(
            categories,
            serviceType === ServiceType.DEAL_SERVICE
                ? "dealServiceRank"
                : "productServiceRank"
        );

        if (!lastCategory) return LexoRank.middle().toString();

        const rank =
            serviceType === ServiceType.DEAL_SERVICE
                ? lastCategory.dealServiceRank
                : lastCategory?.productServiceRank;

        return getNewLexorank(LexoRank.parse(rank)).toString();
    };

    return useCrudOperations<
        ServiceCategorySchema,
        UpdateServiceCategorySchema,
        CreateServiceCategorySchema
    >({
        key: "getServices",
        queryKey,
        mutations: {
            create: createServiceCategoryMutation(),
            update: updateServiceCategoryMutation(),
            delete: deleteServiceCategoryMutation(),
        },
        getCreateEntity: category => {
            const dealServiceRank = getCategoryRank(ServiceType.DEAL_SERVICE);
            const productServiceRank = getCategoryRank(
                ServiceType.PRODUCT_SERVICE
            );

            return {
                dealServiceRank,
                productServiceRank,
                name: category.name!,
            };
        },
        getUpdateEntity: (old, update) =>
            ({
                ...old,
                ...update,
            }) as ServiceCategorySchema,
        getDeleteConfirmTitle: () => "Удаление категории услуг",
    });
};
