import { LexoRank } from "lexorank";
import { useCrudOperations } from "@/hooks/cruds/baseCrud";
import {
    CreateStatusSchema,
    StatusSchema,
    UpdateStatusSchema,
} from "@/lib/client";
import {
    createStatusMutation,
    deleteStatusMutation,
    updateStatusMutation,
} from "@/lib/client/@tanstack/react-query.gen";
import { getMaxByLexorank } from "@/utils/lexorank/max";
import { getNewLexorank } from "@/utils/lexorank/generation";

type Props = {
    statuses: StatusSchema[];
    boardId?: number;
    queryKey: any[];
};

export type StatusesCrud = {
    onCreate: (entity: Partial<CreateStatusSchema>) => void;
    onUpdate: (statusId: number, status: UpdateStatusSchema) => void;
    onDelete: (status: StatusSchema) => void;
};

export const useStatusesCrud = ({
    statuses,
    boardId,
    queryKey,
}: Props): StatusesCrud => {
    return useCrudOperations<
        StatusSchema,
        UpdateStatusSchema,
        CreateStatusSchema
    >({
        key: "getStatuses",
        queryKey,
        mutations: {
            create: createStatusMutation(),
            update: updateStatusMutation(),
            delete: deleteStatusMutation(),
        },
        getCreateEntity: data => {
            if (!boardId) return null;
            const lastBoard = getMaxByLexorank(statuses);
            const newLexorank = getNewLexorank(
                lastBoard ? LexoRank.parse(lastBoard.lexorank) : null
            );
            return {
                name: data.name!,
                boardId,
                lexorank: newLexorank.toString(),
            };
        },
        getUpdateEntity: (old, update) => ({
            ...old,
            name: update.name ?? old.name,
            lexorank: update.lexorank ?? old.lexorank,
        }),
        getDeleteConfirmTitle: () => "Удаление статуса",
    });
};
