import { LexoRank } from "lexorank";
import { useCrudOperations } from "@/hooks/cruds/baseCrud";
import {
    BoardSchema,
    CreateBoardSchema,
    UpdateBoardSchema,
} from "@/lib/client";
import {
    createBoardMutation,
    deleteBoardMutation,
    updateBoardMutation,
} from "@/lib/client/@tanstack/react-query.gen";
import { getMaxByLexorank } from "@/utils/lexorank/max";
import { getNewLexorank } from "@/utils/lexorank/generation";

type UseBoardsOperationsProps = {
    boards: BoardSchema[];
    projectId?: number;
    queryKey: any[];
};

export type BoardsCrud = {
    onCreate: (data: Partial<CreateBoardSchema>) => void;
    onUpdate: (boardId: number, board: UpdateBoardSchema) => void;
    onDelete: (board: BoardSchema) => void;
};

export const useBoardsCrud = ({
    boards,
    projectId,
    queryKey,
}: UseBoardsOperationsProps): BoardsCrud => {
    return useCrudOperations<BoardSchema, UpdateBoardSchema, CreateBoardSchema>(
        {
            key: "getBoards",
            queryKey,
            mutations: {
                create: createBoardMutation(),
                update: updateBoardMutation(),
                delete: deleteBoardMutation(),
            },
            getCreateEntity: data => {
                if (!projectId) return null;
                const lastBoard = getMaxByLexorank(boards);
                const newLexorank = getNewLexorank(
                    lastBoard ? LexoRank.parse(lastBoard.lexorank) : null
                );
                return {
                    name: data.name!,
                    projectId,
                    lexorank: newLexorank.toString(),
                };
            },
            getUpdateEntity: (old, update) => ({
                ...old,
                name: update.name ?? old.name,
                lexorank: update.lexorank ?? old.lexorank,
            }),
            getDeleteConfirmTitle: () => "Удаление доски",
        }
    );
};
