import { LexoRank } from "lexorank";
import statusColors from "@/app/deals/utils/statusColors";
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 { getNewLexorank } from "@/utils/lexorank/generation";
import { getMaxByLexorank } from "@/utils/lexorank/max";

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
            );
            const nextColorIdx = statuses.length % statusColors.length;
            const color = statusColors[nextColorIdx];
            return {
                name: data.name!,
                boardId,
                lexorank: newLexorank.toString(),
                color,
            };
        },
        getUpdateEntity: (old, update) => ({
            ...old,
            name: update.name ?? old.name,
            lexorank: update.lexorank ?? old.lexorank,
        }),
        getDeleteConfirmTitle: () => "Удаление статуса",
    });
};
