import { LexoRank } from "lexorank";
import { useCrudOperations } from "@/hooks/cruds/baseCrud";
import {
    CreateServiceSchema,
    ServiceSchema,
    UpdateServiceSchema,
} from "@/lib/client";
import {
    createServiceMutation,
    deleteServiceMutation,
    updateServiceMutation,
} from "@/lib/client/@tanstack/react-query.gen";
import { getMaxByLexorank } from "@/utils/lexorank/max";
import { getNewLexorank } from "@/utils/lexorank/generation";

type UseServicesProps = {
    queryKey: any[];
    services: ServiceSchema[];
};

export type ServicesCrud = {
    onCreate: (service: CreateServiceSchema) => void;
    onUpdate: (
        serviceId: number,
        service: UpdateServiceSchema,
        onSuccess?: () => void
    ) => void;
    onDelete: (service: ServiceSchema) => void;
};

export const useServicesCrud = ({
    queryKey,
    services,
}: UseServicesProps): ServicesCrud => {
    return useCrudOperations<
        ServiceSchema,
        UpdateServiceSchema,
        CreateServiceSchema
    >({
        key: "getServices",
        queryKey,
        mutations: {
            create: createServiceMutation(),
            update: updateServiceMutation(),
            delete: deleteServiceMutation(),
        },
        getCreateEntity: service => {
            const maxRankStr = getMaxByLexorank(services)?.lexorank;
            const maxRank = maxRankStr ? LexoRank.parse(maxRankStr) : null;

            return {
                ...(service as CreateServiceSchema),
                lexorank: getNewLexorank(maxRank).toString(),
            };
        },
        getUpdateEntity: (old, update) =>
            ({
                ...old,
                ...update,
            }) as ServiceSchema,
        getDeleteConfirmTitle: () => "Удаление услуги",
    });
};
